Index 3D Array with 2D logical array
25 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have an logical array B and an 3D array A. I wish to extract and manipulate values of A for specific k, whereby the values in the first two dimensions are given by B. I was hoping something like
A(B,[1 3 5])
would give me the values specified by B for the first, third and fifth slice of A, but MATLAB doesn't allow this kind of indexing.
In particular, I would like to switch values given by B for certain k (excuse the fauly syntax) akin to
A(B,[1 3 5]) = A(B,[2 4 6])
A minimum example of what I would like to achieve would be:
% coordinate mesh
[X,Y] = meshgrid(1:n,1:m);
% logical array B
B = (X-n/4).^2 + (Y-m/2).^2 < m;
% 3d array A
A = zeros(m,n,9);
A(:,:,1:4) = 1;
A(:,:,5:8) = 2;
A(:,:,9) = 3;
% switching of slices (in fauly syntax)
A(B,[1 2 3 ] = A(B,[5 6 7])
A(B,[5 6 7 ] = A(B,[1 2 3])
I need to do this switching of specific values in the 3. dimension for different slices of A and have not been able to come up with an efficient way of doing this. Any help would be greatly appreciated!
0 Kommentare
Antworten (2)
Stephen23
am 25 Jan. 2020
Bearbeitet: Stephen23
am 25 Jan. 2020
P = size(A,3);
F = @(b,s)repmat(b,1,1,P)&reshape(ismember(1:P,s),1,1,P); % requires >=R2016b
A(F(B,[1,2,3])) = A(F(B,[5,6,7]));
A(F(B,[5,6,7])) = A(F(B,[1,2,3]));
For MATLAB versions earlier than R2016b replace the & operation with bsxfun.
5 Kommentare
Walter Roberson
am 26 Jan. 2020
Stephen's code, like mine, also assumed that the replacements have indices with increasing order. F(B,[1 2 3]) and F(B,[3 2 1]) are the same .
Every technique that uses logical matrices as indexing of the entire array is going to have the same problem of being insensitive to order of the panes. Logical indexing is always just "selected, or not selected" and so always works in linear indexing order, so trying to use logical indexing with [3 2 1] or other non-decreasing order is going to fail unless you take additional steps.
Walter Roberson
am 25 Jan. 2020
You can do things like
mask1 = false(size(A));
mask2 = mask1;
B3 = repmat(B, [1 1 3]);
mask1(:,:,[1 2 3]) = B3;
mask2(:,:,[5 6 7]) = B3;
temp = A(mask1);
A(mask1) = A(mask2);
A(mask2) = temp;
This only works in the case where the pane indexes are increasing. It would not work if, for example, you were swapping A(B, [7 5 6])
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!