How to combine arrays
조회 수: 5 (최근 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
댓글 수: 0
채택된 답변
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
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
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 Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!