Creating array by picking certain elements from another array
6 次查看(过去 30 天)
显示 更早的评论
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!
回答(1 个)
Andrei Bobrov
2018-10-23
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!