I am trying to visualize the data contained a 3D array in MATLAB.
The array is has the dimension of 20*20*40 which all except some of the elements being zero.
I am looking for a way to plot these non-zero points in a scatter plot so that the non-zero points are connected to each other.
here is what I’ve done so far:
b=zeros(6,6,3);
a=[1 1 1;2 2 1;2 1 1;1 2 1;
1 1 2;1 2 2;2 1 2;2 2 2;
6 6 3;6 5 3;5 6 3;5 5 3;
6 6 2;6 5 2;5 6 2;5 5 2];
[r c]=size(a);
for i = 1:r
b(a(i,c-2),a(i,c-1),a(i,c)) = 1;
end
[m n o]=size(b);
figure (1)
[x,y,z] = meshgrid(1:m,1:n,1:o);
scatter3(x(:),y(:),z(:),90,b(:),'filled')
So, what I am after is being able to connect each of the eight points two form to cubic lattices. Any thoughts is much appreciated.

EDIT:
Many thanks to all the experts who helped a lot. Now, I am facing another issue with memory.
The b matrix for my real case would be 1000*1000*2000 and I have the “a” matrix of the size 4,4700,000*3 . All the elements of “a” matrix are integer values.
Although I have up to 48GB of memory availabe. However, in the “for loop” above the program bounces back an “out of memory” error.
Any ideas to make this more memory efficient is greatly appreciated.
I thought I’d answer the follow-up to Amro’s answer, and show how you can automate the connection of edges along a cubic matrix. This answer is intended to be a supplement to Amro’s, and I would recommend incorporating it into that solution so it is easier to read for future viewers.
This starts with
idxfrom Amro’s solution, which contains the linear indices of the corners of the cubes. Below I’ve done it with only one cube so the matrices aren’t grossly large and we can see them here.To visualize, you can plot exactly like in Amro’s answer.