Find the nearest two values in all grid cells to a specified value across a 3D matrix
조회 수: 5 (최근 30일)
이전 댓글 표시
I have a 3D matrix (A)
A = rand(7,100,100);
I want to find the two nearest values in each matrix cell to a specified value (e.g., nearestTo) based on the data from across all 7 layers of the 3D matrix without using a loop.
nearestTo = 0.1; % e.g., this is just an example could be amended if doesn't suit A above
I have managed to get a 2D matrix (100x100) with the indicies of the 1st dimension (7) which are closest to nearestTo:
[~,mindx] = min(abs(A-nearestTo), [], 1);
mindx = squeeze(mindx(1,:,:));
However, I am not sure how to:
- Extract the row and column information and then the value of A based on the 1st dimension index information.
- Repeat the above but extract the second closest value to nearestTo.
The output should be two matrices of 100 x 100 which have the grid cell values of the closest value to nearestTo and the second closest value to nearestTo based on the data from across all 7 layers.
댓글 수: 0
채택된 답변
Rik
2022년 9월 29일
Why squeeze the indices? Just use them to index (for which you need sub2ind).
As for the second closest: the easiest way is to mark the minimum values with inf and then search again.
rng(1) % Fix random seed to get repeatable results
A = rand(7,10,10); % reduce to 10x10 to better visualize results
nearestTo = 0.1; % e.g., this is just an example could be amended if doesn't suit A above
[~,mindx] = min(abs(A-nearestTo), [], 1);
% Determine row-column-page-pairs.
R = mindx; [~,C,P] = ndgrid(1,1:size(A,2),1:size(A,3));
mindx = sub2ind(size(A),R,C,P);
FirstResult = permute(A(mindx),[2:ndims(A) 1]); % remove the first dimension
B = A;
B(mindx) = inf; % Make sure they don't show up as minimum values
[~,mindx] = min(abs(B-nearestTo), [], 1);
% Determine row-column-page-pairs.
R = mindx; [~,C,P] = ndgrid(1,1:size(A,2),1:size(A,3));
mindx = sub2ind(size(A),R,C,P);
SecondResult = permute(B(mindx),[2:ndims(B) 1]); % remove the first dimension
FirstResult,SecondResult
추가 답변 (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!