How to sum a row of variables during a loop
8 ビュー (過去 30 日間)
古いコメントを表示
Hi, dont know if this is possible but I'll ask anyway.
I have a 100*2 matrix. I want to check if each value equals 1 or zero, if it's 1 multiply it by some number and have that saved as some new variable. I then want to sum those variables per row and store those totals in a new 100*1 matrix.
I understand this code doesnt make actual sense but it indicates what im trying to achieve. Can anyone point me in the right direction?
Thanks in advance to anyone for help, it's really appreciated.
val1 = 0;
val2 = 0;
multiplier1 = 10
multiplier2 = 15
for i = 1:100
if matrix(i,1) == 1
val1(i) = matrix(i,1)*multiplier1
else
end
if matrix(i,2) == 1
val2(i) = matrix(i,2)*multiplier2
else
end
rowtotal(i) = val1(i) +val2(i)
end
2 件のコメント
madhan ravi
2019 年 3 月 16 日
It looks trivial, what do you want to do when no of val1 is not equal to val2?
採用された回答
Star Strider
2019 年 3 月 16 日
See if this does what you want:
matrix = randi([0 1], 100, 2); % Create ‘matrix’
multiplier1 = 10;
multiplier2 = 15;
val = bsxfun(@times, matrix, [multiplier1, multiplier2]);
rowtotal = sum(val,2);
Note that you do not have to test for a given element being 0 or 1, since the 0 values will remain 0 and only the 1 values will be multiplied.
6 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!