Calculate the sum of these two vectors using loops. Can't use sum()

2 views (last 30 days)
Use loops to calculate the sum of two row vectors a & b, each of dimension 9. c(i)=a(i) + b(i) for i=1:9;
My current code looks like this:
clear;
a=zeros(1,9);
b=zeros(1,9);
c=zeros(1,9);
for i=1:9;
c(i)= a(i)+ b(i);
end;
disp(c);

Answers (4)

Torsten
Torsten on 9 Apr 2015
Your code is ok although you just could have set
c=a+b;
I wonder why you are supposed to use a loop.
Best wishes
Torsten.

Eric
Eric on 9 Apr 2015
My output is just not right though.
output:
0 0 0 0 0 0 0 0 0
  5 Comments
Torsten
Torsten on 9 Apr 2015
You have
a=[0 0 0 0 0 0 0 0 0]
b=[0 0 0 0 0 0 0 0 0]
What you do in the loop is to sum a and b componentwise, thus
c=[0+0 0+0 0+0 0+0 0+0 0+0 0+0 0+0 0+0]
and the result is
c=[0 0 0 0 0 0 0 0 0]
Best wishes
Torsten.

Sign in to comment.


Eric
Eric on 9 Apr 2015
Ok, but I'm trying to replace the values of zero with 1,2,3...9, so how do I replace the loop to sum numbers 1:9
Sorry if my question wasn't clear enough.
  1 Comment
Torsten
Torsten on 9 Apr 2015
If you want to sum numbers 1,...,9:
summe=0;
for i=1:9
summe=summe+i;
end
disp(summe);
Best wishes
Torsten.

Sign in to comment.


Eric
Eric on 9 Apr 2015
I attached the question to make things more clear

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!