Random number of matrix within certain value

1 visualización (últimos 30 días)
Lee Peng Yi
Lee Peng Yi el 4 de Oct. de 2016
Editada: Lee Peng Yi el 5 de Oct. de 2016
I saw a solution at Copy certain number from one matrix to another. It was very similar to what i'm doing at the moment. Currently i'm using this DataD.xlsx to and import the matrix directly to my Matlab. I need to change the value of the matrix on the second column and copy it into new column but keep the value 1. Such as
1
3
4
5
1
1
2
1
into
1 1 %copy
3 2 %random
3 1 %random
3 1 %copy above value
1 1 %copy
1 1 %copy
2 8 %random
7 3 %copy
7 1 %random
7 1 %copy above value
Each of the value is randomized between 0 until 9 but whenever the Matlab read the number 1, it just copy it to new column. If the third row is change to 1, the following column is also change to 1. Same also with row number 9. if it random and get 1, the following row also will change to 1. How can i achieve this?

Respuestas (1)

Sima
Sima el 4 de Oct. de 2016
I would do something like this:
original_ones_idxs = input==1;
number_of_random = sum(original_ones_idxs ==0);
rand_numbers=randi([0,9],number_of_random);
rand_values=-1*ones(size(input)); %-1 just to have some invalid number...
rand_values(~original_ones_idxs)=rand_numbers;
random_ones_idxs=rand_values==1;
rand_values(random_ones_idxs+1)=1; %putting 1 in the next row if there was a random 1
rand_values(original_ones_idxs)=1; %copying the original ones
if length(rand_values)>length(input) %if the random 1 was in the last row make sure not to overflow
rand_values=rand_values(1:end-1)
end
  1 comentario
Lee Peng Yi
Lee Peng Yi el 5 de Oct. de 2016
Editada: Lee Peng Yi el 5 de Oct. de 2016
[out] = xlsread('DataD.xlsx');
t = out(:,1);
v = out(:,2);
Z=[t,v];
original_ones_idxs = input==1;
number_of_random = sum(original_ones_idxs ==0);
rand_numbers=randi([0,9],number_of_random);
rand_values=-1*ones(size(input)); %-1 just to have some invalid number...
rand_values(~original_ones_idxs)=rand_numbers;
random_ones_idxs=rand_values==1;
rand_values(random_ones_idxs+1)=1; %putting 1 in the next row if there was a random 1
rand_values(original_ones_idxs)=1; %copying the original ones
if length(rand_values)>length(input) %if the random 1 was in the last row make sure not to overflow
rand_values=rand_values(1:end-1)
end
rand_values is unused

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by