How to sort a 3D matrix according to the value of each element?
10 次查看(过去 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!