[英]Visualize a three-dimensional array like cubic lattice using MATLAB
我想使用MATLAB可視化三維數組,就像立方晶格一樣。
我已經閱讀了如何在Matlab中繪制3D網格(立方體) ,以及使用三維數組 繪制 簡單立方晶格
如果數組中的元素只有0和1,我知道如何使用三維數組繪制一個簡單的立方晶格,小立方體具有相同的大小。
但是,現在我有一個像這樣的三維數組,
cube(:,:,1) =
1 0 1
0 1 1
2 1 0
cube(:,:,2) =
0 0 1
1 5 1
0 1 0
cube(:,:,3) =
1 1 1
0 1 1
2 0 1
數組立方體的值除了0和1.我想像立方晶格一樣可視化數組,其中立方體(:,:,1)表示立方晶格的第一層,
cube(:,:,2) denotes the second floor, and
cube(:,:,3) the third floor.
值0表示無,而值1表示小藍色立方體。
大於1的值表示球體,球體的直徑根據值而變化。 期望的結果是這樣的:
三維陣列的可視化,1表示小綠色立方體,0表示無,大於1的值表示白色球體,球體的直徑根據值而變化。
為了更清楚地解釋我的問題,展示一個二維數組的可視化
1表示小黑球,0表示無,大於1的值表示白球,球的直徑根據該值而變化。
所需的效果圖
當立方體的邊長為1時,它是好的
當設置邊長為2時,drawCube([ix,iy,iz],2,Royal_Blue)。 出現問題,立方體重疊,
讓我告訴你我的嘗試。 它基於獨立繪制每個立方體和圓。 如果A
很大,這將是緩慢的。
結果:
代碼應該是自我解釋的。
% Create some data. This piece of code just creates some matrix A with
% some 1s and 0s and inserts a 2 and a 3 to specific positions. Subsitute
% this with your own data matrix.
th=0.2;
A=double(rand(10,10,10)<th);
A(1,1,1)=2;
A(5,5,5)=3;
% A nice color. I just dont like the standard blue so I picked another one.
Royal_Blue=[65 105 225]/255;
%%%%%%%%%%%%%%%%%%%%%%
%% Draw cubes
% Obtain all the linear indexes (search mathworks for help between
% subscripts vs linear indices) of the locations where a cube is wanted
% (A==1)
ind=find(A==1);
% Create a figure
fig=figure();
hold on
% Draw the cubes one by one
for ii=1:length(ind)
% For each linear index get its subscript (that also
% will be x,y,z position)
[ix,iy,iz]=ind2sub(size(A),ind(ii));
% Use the drawcube function to draw a single cube in the
% desired position with the desired size (1) and colour.
drawCube([ix,iy,iz],1,Royal_Blue);
end
% Nice plotting code. This just makes the drawing nicer.
camlight left
lighting gouraud
axis equal
axis off
view(-50,25)
%%%%%%%%%%%%%%%
%% Now draw the spheres
% This code is the same as the previous one but I just draw
% spheres instead of cubes.
ind=find(A>1);
% create an sphere
[X,Y,Z] = sphere;
for ii=1:length(ind)
[ix,iy,iz]=ind2sub(size(A),ind(ii));
% scale sphere
Xs=X*A(ix,iy,iz)/2;
Ys=Y*A(ix,iy,iz)/2;
Zs=Z*A(ix,iy,iz)/2;
surf(Xs+ix,Ys+iy,Zs+iz,'edgecolor','none','facecolor',[1 1 1]);
end
% Change the background colour to black
whitebg(fig,'k')
% MAke sure it stays black
set(gcf, 'InvertHardCopy', 'off');
函數drawCube
如下:
function drawCube( origin, size,color)
% From
% http://www.mathworks.com/matlabcentral/newsreader/view_thread/235581
if nargin<3
color='b';
end
x=([0 1 1 0 0 0;1 1 0 0 1 1;1 1 0 0 1 1;0 1 1 0 0 0]-0.5)*size+origin(1);
y=([0 0 1 1 0 0;0 1 1 0 0 0;0 1 1 0 1 1;0 0 1 1 1 1]-0.5)*size+origin(2);
z=([0 0 0 0 0 1;0 0 0 0 0 1;1 1 1 1 0 1;1 1 1 1 0 1]-0.5)*size+origin(3);
for i=1:6
h=patch(x(:,i),y(:,i),z(:,i),color);
set(h,'edgecolor','none')
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.