Info
此问题已关闭。 请重新打开它进行编辑或回答。
How do I put these 'if' statements in the same loop?
1 次查看(过去 30 天)
显示 更早的评论
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]
0 个评论
回答(2 个)
David Sanchez
2013-11-28
You can write C like this:
C=[AB(1,1)==AB(1,2); AB(2,1)==AB(2,2)]
to achieve the same.
1 个评论
David Sanchez
2013-11-28
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)
2013-11-28
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
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!