Creating array by picking certain elements from another array
5 views (last 30 days)
Show older comments
Let's say I am given two arrays A and B of size 100x100x5. The entries of A are either NaN or integers from 1 to 10, such that the integers along the third dimension are always unique. For instance, A(50,50,:) might look like
A(50,50,:) = [1,NaN,6,2,3,NaN];
The array B contains NaN-entries at the same places as A, and random values at the other positions. So perhaps
B(50,50,:) = [21,NaN,42,-42,-21,NaN];
In my context, A is saving the component index of the points given in B. I would like to create a new array C of size 100x100x10. The third dimension should represent the component, the values in C should represent the values of the points given by B. Hence the entries of C should be defined by C(i,j,k) = B(i,j,m) if A(i,j,m) = k, and C(i,j,k) = NaN if k is not contained in A(i,j,:). In the above example, I should get
C(50,50,:) = [21,-42,-21,NaN,NaN,42,NaN,NaN,NaN,NaN];
I hope you get the idea. I am hoping to find a simpler way for solving this than some for- and if-loops. Of course it would suffice if one could create the matrix C(:,:,1), it is not a problem to run a for-loop over the components. Thanks for your help!
2 Comments
Answers (1)
Andrei Bobrov
on 23 Oct 2018
s = size(A);
[ii,jj,~] = ndgrid(1:s(1),1:s(2),1:s(3));
ij = [ii(:),jj(:),A(:),B(:)];
ij = ij(~isnan(ij(:,3)),:);
out = accumarray(ij(:,1:3),ij(:,4),s + [0,0,s(3)],[],nan);
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!