Adding a third array for comparison

I have a three main array the consist of sub array themselves and I have managed to combine two of the main array in the loop shown below into a single new array. The issue I am facing is that I am not really certain of how to add the third main array. Here is the issue:
Given: A = {A1 A2 A3} B = {B1 B2 B3} C = {C1 C2 C3}
Desired output: V = {A1+B1+C1 A1+B1+C2 A1+B1+C3 A1+B2+C1 A1+B2+C2 A1+B2+C3 ..... and so on.
Current output: V = {A1+B1 A1+B2 A1+B3 A2+B1 A2+B2 A2+B3 A3+B1 A3+B2 A3+B3}
Code:
b = 1;
i = 1;
v = 1;
if true
if b <= length(B)
while b <= length(B)
V{v} = A{i} + B{b}
b = b + 1;
v = v + 1;
end
end
while true
if b > length(B)
b = 1;
i = i + 1;
if i <= length(A)
while b <= length(B)
V{v} = A{i} + B{b}
b = b + 1;
v = v + 1;
end
else
return
end
end
end
end

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 1 月 27 日

0 投票

V = cellfun(@(m1,m2,m3) m1+m2+m3, A, B, C, 'uniform', 0)

4 件のコメント

Andrew Tubbs
Andrew Tubbs 2021 年 1 月 27 日
The cellfun command does not work, this outputs an array with three cells, not the 27 cells that the combinations come out to. I am looking for a way to add the third set of array into the current structure of the program.
Walter Roberson
Walter Roberson 2021 年 1 月 27 日
[C1, C2, C3] = ndgrid(1:3);
V = arrayfun(@(c1,c2,c3) A{c1}+B{c2}+C{c3}, C1(:), C2(:), C3(:), 'uniform', 0).';
Andrew Tubbs
Andrew Tubbs 2021 年 1 月 27 日
I am not looking for a function, just a litteral addition to the code I have posted in the same format.
Walter Roberson
Walter Roberson 2021 年 1 月 27 日
Your code is too complicated
loop over the indices for the elements of A
loop over the indices for the elements of B
loop over the indices for the elements of C
calculate index A plus index B plus index C
store it to the list of results
end of loop
end of loop
end of loop

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2021 年 1 月 27 日

コメント済み:

2021 年 1 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by