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

1 view (last 30 days)
Sojung Youn
Sojung Youn on 8 Dec 2021
Commented: Sojung Youn on 9 Dec 2021
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
Many thanks!

Accepted Answer

_ on 8 Dec 2021
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)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!