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

 采纳的回答

  • 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!

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by