How to sort a 3D matrix according to the value of each element?
조회 수: 9 (최근 30일)
이전 댓글 표시
Hello,
I have a 3D matrix (attached). What I wish to accomplish is to sort this matrix, element by element, such that the highest value(s) are towards the bottom (i.e. last rows) when I visualize it and vice versa.
I have tried the sort/sortrows commands but haven't had much success with my current knowledge. If anyone can nudge me in the right direction, I'd be grateful.
댓글 수: 0
답변 (2개)
Simon Chan
2021년 8월 24일
If I understand correctly, you would like the larger value(s) in the last rows and the largest one on the bottom right hand corner (last row and last column).
If this is not the case, the following code does not work.
clear; clc;
load('Numbers_3D.mat');
[Ny,Nx,Nz] = size(num);
sortnum = zeros(size(num));
for k = 1:Nz
data = num(:,:,k);
sortnum(:,:,k) = transpose(reshape(sort(data(:)),Nx,Ny));
end
댓글 수: 0
Wan Ji
2021년 8월 24일
편집: Wan Ji
2021년 8월 24일
I think you want make something gif to show how the numbers are sorted?
% sort show
% show bubbling
clc;clear
% load('Numbers_3D.mat');
% a = num(1:32,:,:); clear num
a = rand(30,50,40);
[x,y,z] = meshgrid(1:size(a,1), 1:size(a,2), 1:size(a,3));
x = x(:);
y = y(:);
z = z(:);
Idx = sub2ind(size(a),x,y,z);
scatter3(x,y,z,10,a(Idx),'filled')
axis equal
% colr = gray;
colr = jet;
colr = colr(end:-1:1,:);
colormap(colr)
view(-163,-66)
for k = 1:1:size(a,1)
for r = size(a,1):-1:k+1
for i = 1:1:size(a,2)
for j = 1:1:size(a,3)
if(a(k,i,j)<a(r,i,j))
a([k,r],i,j) = a([r,k],i,j);
end
end
end
scatter3(y,x,z,10,a(Idx),'filled')
view(-163,-66)
xlabel('Dimension 2'); ylabel('Dimension 1'); zlabel('Dimension 3');
axis equal
colormap(colr); colorbar;
pause(0.001)
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!