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

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);

답변 (4개)

Torsten
Torsten 2015년 4월 9일

0 개 추천

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 2015년 4월 9일
My output is just not right though.
output:
0 0 0 0 0 0 0 0 0

댓글 수: 5

Ilham Hardy
Ilham Hardy 2015년 4월 9일
편집: Ilham Hardy 2015년 4월 9일
Why do you think this is incorrect?
isn't it suppose to work something like this:
a + b = c
1 1 1 1 1 1 1 1 1 + 1 1 1 1 1 1 1 1 1 = 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 + 2 2 2 2 2 2 2 2 2 = 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 + 3 3 3 3 3 3 3 3 3 = 6 6 6 6 6 6 6 6 6
etc etc up to 9
and then add up all the c's?
Or is my understanding of vectors wrong?
It actually works like that, but in your original post you're basically doing 0+0=0...
a=ones(1,9);
b=ones(1,9)*3;
c=zeros(1,9);
c=a+b;
disp(a);
disp(b);
disp(c);
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.

댓글을 달려면 로그인하십시오.

Eric
Eric 2015년 4월 9일

0 개 추천

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

If you want to sum numbers 1,...,9:
summe=0;
for i=1:9
summe=summe+i;
end
disp(summe);
Best wishes
Torsten.

댓글을 달려면 로그인하십시오.

Eric
Eric 2015년 4월 9일

0 개 추천

I attached the question to make things more clear

댓글 수: 1

If this is the question, your original code is correct.
Best wishes
Torsten.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

질문:

2015년 4월 9일

댓글:

2015년 4월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by