Info

This question is closed. Reopen it to edit or answer.

How do I put these 'if' statements in the same loop?

1 view (last 30 days)
Filip
Filip on 28 Nov 2013
Closed: MATLAB Answer Bot on 20 Aug 2021
I want to make a matrice 2*2 with random 1 and 0. Then I want to make a new matrice 2*1 that dispalys a 1 only if both rows are 1. I have written the code below and it works. But I feel that there is a much nicer way to accomplish the task since the code would be unpractical for a bigger matrice. Any suggestions?
AB=randi(2,2,2)-1
if AB(1,1)==1 & AB(1,2)==1
C1=1;
else
C1=0;
end
if AB(2,1)==1 & AB(2,2)==1
C2=1;
else
C2=0;
end
C=[C1;C2]

Answers (2)

David Sanchez
David Sanchez on 28 Nov 2013
You can write C like this:
C=[AB(1,1)==AB(1,2); AB(2,1)==AB(2,2)]
to achieve the same.
  1 Comment
David Sanchez
David Sanchez on 28 Nov 2013
I mean, your all code will be:
AB=randi(2,2,2)-1;
C=[AB(1,1)==AB(1,2); AB(2,1)==AB(2,2)];

Jos (10584)
Jos (10584) on 28 Nov 2013
AB=randi(2,2,2)-1
C = all(AB==1,1) % per column true if both rows equal 1
C = C.' % you wanted a 2-by-1 vector

Community Treasure Hunt

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

Start Hunting!