How to combine arrays

1 view (last 30 days)
Jonathan
Jonathan on 23 Mar 2020
Edited: Stephen23 on 23 Mar 2020
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

Accepted Answer

Sriram Tadavarty
Sriram Tadavarty on 23 Mar 2020
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 Comments
Sriram Tadavarty
Sriram Tadavarty on 23 Mar 2020
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 on 23 Mar 2020
Edited: Stephen23 on 23 Mar 2020
"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:

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!