Suming vectors which are produced in a loop

2 Ansichten (letzte 30 Tage)
Steven Martin
Steven Martin am 27 Mär. 2018
Kommentiert: Stephen23 am 27 Mär. 2018
Say I have a loop which returns three vectors:
for i = 1:3
V = [i; 2*i; 3*i];
end
returning
V = [1; 2; 3] V = [2; 4; 6] V = [3; 6; 9]
how do i then sum these to get
sumV = [1+2+3; 2+4+6; 3+6+9]
  1 Kommentar
Stephen23
Stephen23 am 27 Mär. 2018

Why not just

>> 6:6:18
ans =
  6   12   18

Or

>> 6*(1:3)
ans =
  6   12   18

Or using bsxfun:

>> sum(bsxfun(@times,1:3,(1:3).'),1)
ans =
  6   12   18

Or if you really want to use a loop (which is a waste of MATLAB):

>> V = zeros(1,3);
>> for k = 1:numel(V), V(k)=sum(k*(1:3)); end
>> V
V =
  6   12   18

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Birdman
Birdman am 27 Mär. 2018
Bearbeitet: Birdman am 27 Mär. 2018
n=3;
sumV=zeros(n,1);
for i = 1:n
V = [i; 2*i; 3*i];
sumV(i,1)=sum(V,1);
end
  2 Kommentare
Steven Martin
Steven Martin am 27 Mär. 2018
This then returns 3 vectors I only want it to return one (the last one) as I want to use this in my code later on
Birdman
Birdman am 27 Mär. 2018
Not 3 vectors, it returns only one vector:
sumV =
6
12
18

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by