Using conditional IF statement
1 回表示 (過去 30 日間)
古いコメントを表示
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
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.
採用された回答
その他の回答 (1 件)
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.
0 件のコメント
参考
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!