How to sum a row of variables during a loop

5 ビュー (過去 30 日間)
Stephen
Stephen 2019 年 3 月 16 日
コメント済み: Star Strider 2019 年 3 月 16 日
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
madhan ravi 2019 年 3 月 16 日
It looks trivial, what do you want to do when no of val1 is not equal to val2?
Stephen
Stephen 2019 年 3 月 16 日
Hi madhan, thanks for commenting. This example is probably too far from what Im actually trying to achieve, I asked a more complete question in a comment below if you are interested in lending a hand.
Thanks.

サインインしてコメントする。

採用された回答

Star Strider
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 件のコメント
Stephen
Stephen 2019 年 3 月 16 日
Wow thank you so much this is perfect!
I must read up on logical indexing.
Thanks again I really appreciate you taking the time to put this together, you're a life saver!!
Star Strider
Star Strider 2019 年 3 月 16 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by