Calculate the sum of these two vectors using loops. Can't use sum()
Ältere Kommentare anzeigen
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);
Antworten (4)
Torsten
am 9 Apr. 2015
0 Stimmen
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
am 9 Apr. 2015
5 Kommentare
Ilham Hardy
am 9 Apr. 2015
Bearbeitet: Ilham Hardy
am 9 Apr. 2015
Why do you think this is incorrect?
nhagen
am 9 Apr. 2015
It actually works like that, but in your original post you're basically doing 0+0=0...
nhagen
am 9 Apr. 2015
a=ones(1,9);
b=ones(1,9)*3;
c=zeros(1,9);
c=a+b;
disp(a);
disp(b);
disp(c);
Torsten
am 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.
Kategorien
Mehr zu Programming finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!