How to use a for loop to calculate the sum of a row vector?

I have the values x-[1, 23, 43, 72, 87, 56, 98, 33] How do you calculate the sum (which should equal 413) using a for loop?

 Accepted Answer

Stalin Samuel
Stalin Samuel on 25 Nov 2015
Edited: Stephen23 on 21 Dec 2018
x = [1, 23, 43, 72, 87, 56, 98, 33] ;
y = 0;
for n = 1:length(x)
y = y + x(n);
end

8 Comments

Better to use a variable with a name other than 'sum', since that is the name of an existing MATLAB function.
Needed this, thanks for the post!
Ok, now how do you get it to display the result?
what about multiply these elements together?
disp(y) %this will display the result
how do you make this loop into a function??

Sign in to comment.

More Answers (1)

Aza Xongo
Aza Xongo on 16 Apr 2019
Edited: Aza Xongo on 16 Apr 2019
Write a program (using loops) that calculates and displays the sum of all the elements of x=[2 -5 6 7; -4 8 -5 6];(its a question)

1 Comment

X =['enter an array>']; m = length(x); Sum = 0; For i = 1:m Sum = sum + X(i); end Disp(sum)
IF you want single sum. It you wish iterations remove semicolon from end of X(i).

Sign in to comment.

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!