How do I sum many vectors together by using 'for' loop?

Hi,
I am currently working to find the center of a few random points. My idea is to take the sum of all the points and find the average. I have tried to use a simple 3D example of adding two vectors together by using the 'for' loop.
pos_swarm = zeros(3,s);
pos_swarm(:,1) = [0,0,0];
pos_swarm(:,2) = [5,5,5];
sum = zeros(3,s);
for i = 1:s
sum(:,i) = pos_swarm(:,1) + pos_swarm(:,2);
average = sum ./ s
end
How do I add 'n' number of vectors together? Greatly appreciate if anyone can help me with this. :)
Regards, Thomas

 Accepted Answer

  • There is nothing 3D in your example. Your pos_swarm is 2d.
  • DO NOT use sum as a variable name, it prevents you from using the sum function, which is really what you want to do.
  • matlab can get you the average directly, using mean
numvectors = 100;
pos_swarm = randi([0 20], numvectors, 3) %build a 2d matrix of vectors for demo
pos_sum = sum(pos_swarm) %simple!
pos_average = mean(pos_swarm) %simple!

More Answers (0)

Categories

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

Asked:

on 4 Mar 2016

Commented:

on 19 Mar 2016

Community Treasure Hunt

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

Start Hunting!