Random number of matrix within certain value

조회 수: 1 (최근 30일)
Lee Peng Yi
Lee Peng Yi 2016년 10월 4일
편집: Lee Peng Yi 2016년 10월 5일
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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by