How to combine arrays

1 次查看(过去 30 天)
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 CenterFile 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