필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 1 (최근 30일)
Filip
Filip 2013년 11월 28일
마감: MATLAB Answer Bot 2021년 8월 20일
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]

답변 (2개)

David Sanchez
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
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)
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

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by