How to combine arrays

2 ビュー (過去 30 日間)
Jonathan
Jonathan 2020 年 3 月 23 日
編集済み: Stephen23 2020 年 3 月 23 日
I have 3 2D arrays, let's call them A, B, C of equal dimensions.
What I want to do is return a combined array 'D' which has the same dimension as A, B, C. Where the value in A, B, C is 0, it will remain as 0. However, if a 1 appears in place in A,B,C it will then return a 1 at that particular location.
A =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
B =
0 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0
0 1 1 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
C =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

採用された回答

Sriram Tadavarty
Sriram Tadavarty 2020 年 3 月 23 日
Hi,
The following should help you do it:
D = zeros(size(A));
D(A==1 | B == 1 | C == 1) = 1;
Hope this helps.
Regards,
Sriram
  5 件のコメント
Sriram Tadavarty
Sriram Tadavarty 2020 年 3 月 23 日
Do accept the answer, if it helps for the question asked.
Ok, if that is the case, you can try the following:
% Assuming S is an array of arrays (implies M x N x P)
% M - number of rows
% N - number of columns
% P - number of such matrices
D = zeros(M,N);
index1Loc = sum(S,3) ~= 0;
D(index1Loc) = 1;
% If you already have the variables, take a matrix
D = zeros(M,N);
D(A) = D(A)+1;
D(B) = D(B)+1;
D(C) = D(C)+1; % You need add up manually all the variables
D = (D >= 0);
Hope these helps.
Regards,
Sriram
Stephen23
Stephen23 2020 年 3 月 23 日
編集済み: Stephen23 2020 年 3 月 23 日
"I don't know how I will store the arrays yet."
If the sizes are the same then one ND array would be best. It would trivial to access using indexing.
"I was thinking maybe in a container array."
A container array would also work, but likely would be slightly less efficient.
"Maybe I should store these data in separate variables then and then add it to a container array?"
That would be about the worst way to approach this. Accessing variable names dynamically is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read more:

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by