How to If certain number is in one column, record another number in another column

조회 수: 4 (최근 30일)
Hello,
I am very new to matlab and trying to learn how to code my project, any help would be much appreciated.
Currently, I am trying to code a script that if there is one number already avaliable at one column, it would put the other number in the other column. For example, I am trying to get number 0, 1 randomly coded in to column 2 and 3. If there is a 0 on column 2, I would like to have 1 on column 3 and vice versa. So it would look something like this.
A = [ 1 0 1
2 1 0
3 1 0
4 0 1 ]
I managed to get the 0 and 1 randomly distrbuted on column 2, but I am having trouble with putting the numbers in for column 3.
Would anyone know an effiecnt way to do it?
Below is the code that I was trying to use.
Datafile(:,2) = mod(reshape(randperm(96*1), 96, 1), 2) %the 96 is there becuase I just have 96 rows
Datafile(96:3) =0
if Datafile(:,2) == 0
Datafile(:,4) = 1
end
Many thanks!

채택된 답변

Voss
Voss 2021년 12월 8일
If the value in the second column is x, then the value of the fourth column should be 1-x. This is true because 1-0=1 and 1-1=0. (If you need to do a similar thing with numbers other than 0 and 1, a similar linear transform can be found: if column 2 is x, an element from {a,b}, then column 4 is (a+b)-x. thus, a->b and b->a.)
Datafile(:,2) = mod(reshape(randperm(96*1), 96, 1), 2);
% Datafile(96:3) =0; % btw, this line has no effect because 96:3 is an empty array
% Datafile(:,3) = 0; % do this to initialize the third column to all zeros, but even this is unnecessary because
Datafile(:,4) = 1-Datafile(:,2); % this line will put the fourth column in place (filling in the third with zeros if it's not there aleady)

추가 답변 (0개)

카테고리

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