How to sum a row of variables during a loop
10 views (last 30 days)
Show older comments
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
on 16 Mar 2019
It looks trivial, what do you want to do when no of val1 is not equal to val2?
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!