How do I sum multiple vectors inside an array?

I am trying to sum vectors for specific columns of an array using cell arrays but it is summing all the components of each vector and is returning one value which is the problem. I want it to sum as vectors should with x components and y components and return a vector.
I am trying to iterate this in a loop for each column so if there is also a way without indexing by just using a loop, feel free to let me know. Thanks in advance!

4 件のコメント

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 5 月 9 日
編集済み: KALYAN ACHARJYA 2019 年 5 月 9 日
Can you elaborate with example and what result you are expecting?
Stephen23
Stephen23 2019 年 5 月 9 日
編集済み: Stephen23 2019 年 5 月 9 日
It sounds like accumarray might do what you want.
Please provide a simple working example, complete with input and output arrays.
Aaron Rapliza
Aaron Rapliza 2019 年 5 月 9 日
編集済み: Aaron Rapliza 2019 年 5 月 9 日
Say
v1 = [1 2]
v2 = [3 4]
v3 = [5 6]
v4 = [7 8]
and f = {v1 v2
v3 v4}
I want the sum of the vectors in the first column i.e. f{1,:}
then the result would be:
[1+3 2+4]
[4 6]
Aaron Rapliza
Aaron Rapliza 2019 年 5 月 9 日
編集済み: Jan 2019 年 5 月 9 日
I am trying to calculate the acceleration for n bodies of a solar system and since the acceleration is affected by the other bodies I have to sum the forces of each planet it is being affected by
This is a section of the code I have:
for i = 1:n
for x = 1:n
if i ~= x
f{i,x} = G * (p(x,:) - p(i,:)) * ((mass(i) * mass(x)) / (norm(p(x,:) - p(i,:))^3));
a{i,x} = (1 / mass(i)) * (sum(f{i,:}));
end
end

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2019 年 5 月 9 日
編集済み: Jan 2019 年 5 月 9 日

0 投票

You can use the force between two bodies twice:
f = zeros(n, n, 3);
for i = 1:n
for x = i+1:n
f_ix = G * (p(x,:) - p(i,:)) * ...
((mass(i) * mass(x)) / (norm(p(x,:) - p(i,:))^3))
f(i,x,:) = f_ix;
f(x,i,:) = -f_ix;
end
end
% Calculate the total acceleration *after* getting all forces:
a = sum(f, 3) ./ mass; % With auto-expanding since R2016b

カテゴリ

ヘルプ センター および File ExchangeComputational Geometry についてさらに検索

質問済み:

2019 年 5 月 9 日

編集済み:

Jan
2019 年 5 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by