Using conditional IF statement

조회 수: 4 (최근 30일)
summyia qamar
summyia qamar 2016년 12월 19일
답변: Steven Lord 2016년 12월 19일
I have a matrix A and I generate B=randi([0,1],7,3).I want C=A*B only if sum of each row of B=1..I tried this..
A=[1 0 0 1 0 1 1
0 1 1 1 0 0 1
1 0 0 1 1 0 0
1 0 0 0 1 0 1
1 1 0 0 0 1 0
0 1 0 0 0 1 1]
for k=1:numIterations
B=randi([0,1],7,3);
if sum(B,2)==1;
C=A*B;
end
end
how to use IF condition in this case?
  댓글 수: 2
Walter Roberson
Walter Roberson 2016년 12월 19일
What do you want to have happen if the condition is met multiple times within the "for k" loop? You are overwriting all of C each time.
summyia qamar
summyia qamar 2016년 12월 19일
thankyou..I skipped C(k)

댓글을 달려면 로그인하십시오.

채택된 답변

Roger Stafford
Roger Stafford 2016년 12월 19일
if all(sum(B,2)==1)
  댓글 수: 1
summyia qamar
summyia qamar 2016년 12월 19일
I tried this.
A=[1 0 0 1 0 1 1
0 1 1 1 0 0 1
1 0 0 1 1 0 0
1 0 0 0 1 0 1
1 1 0 0 0 1 0
0 1 0 0 0 1 1];
for k=1:numIterations
B=randi([0,1],7,3);
if all(sum(B,2)==1)
C=A*B
end
end
[B C(ones(7,1))]
and result is C =
1 2 1
0 4 0
2 1 0
2 1 0
1 1 1
0 2 1
ans =
0 0 1 1
1 0 0 1
1 0 1 1
1 1 0 1
1 0 1 1
1 0 0 1
0 0 1 1
row 3 is not upto the condition

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2016년 12월 19일
Don't generate B randomly, or at least not the way you're generating it. Your constraint on B is that each row must have exactly one nonzero value. So generate the index of the column in each row that contains the nonzero value and use that to generate a B matrix that is guaranteed to satisfy your constraint.
numRows = 10;
numCols = 5;
rowind = (1:numRows).';
colind = randi(numCols, numRows, 1);
B = accumarray([rowind, colind], 1, [numRows, numCols]);
check = all(sum(B, 2) == 1)
The sz input to accumarray is necessary for the (unlikely) case where no row has a 1 in the last column, to ensure B is the correct size.

카테고리

Help CenterFile Exchange에서 Frequency-Domain Analysis에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by