Random number of matrix within certain value

1 次查看(过去 30 天)
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?

回答(1 个)

Sima
Sima 2016-10-4
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 个评论
Lee Peng Yi
Lee Peng Yi 2016-10-5
编辑:Lee Peng Yi 2016-10-5
[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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by