How to sum a row of variables during a loop

10 views (last 30 days)
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 Comments
madhan ravi
madhan ravi on 16 Mar 2019
It looks trivial, what do you want to do when no of val1 is not equal to val2?
Stephen
Stephen on 16 Mar 2019
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.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 16 Mar 2019
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 Comments
Stephen
Stephen on 16 Mar 2019
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!!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!