Search code examples
arraysmatlabplotmatlab-figure

How could one plot 3D matrix in 2D?


I am new in coding with matlab. I have the following 3D matrix

>> Xc
Xc(:,:,1) =

   -1.6803   -1.6803   -1.6803   -1.6803        
   -1.1803   -1.1803   -1.1803   -1.1803         
   -0.6803   -0.6803   -0.6803   -0.6803        
  -14.1803  -14.1803  -14.1803  -14.1803         
Xc(:,:,2) =

   -1.6803   -1.6803   -1.6803   -1.6803         
   -1.1803   -1.1803   -1.1803   -1.1803         
   -0.6803   -0.6803   -0.6803   -0.6803        
  -14.1803  -14.1803  -14.1803  -14.1803         
.
.
.
.
Xc(:,:,64) =

   -7.5112   -7.5112   -7.5112   -7.5112         
   -4.8926   -4.8926   -4.8926   -4.8926         
   -0.0081   -0.0081   -0.0081   -0.0081         
  -13.7577  -13.7577  -13.7577  -13.7577        

how can I plot the first column of all these 64 pieces in a heat map sort of plot parallel to each others?


Solution

  • To plot slices along the second dimension in 3D

    You can do that with the slice function. Note that this function generates surface objects (like surf does), in which the row index corresponds to the y axis and the column index to the x axis. So the first two coordinates in Xc have to be swapped with permute:

    [ii, jj, kk] = ndgrid(-2:.5:2, -2:.8:2, -2:.4:2);
    Xc = jj.*exp(-ii.^2-jj.^2-kk.^2); % example adapted from `slice` documentation
    slice(permute(Xc, [2 1 3]), [], 1:size(Xc,2), [])
    xlabel row, ylabel column, zlabel page
    view(67, 31)
    colorbar
    

    enter image description here

    To plot a single slice along the second dimension in 2D

    It suffices to index Xc in the second dimension, squeeze into a matrix with permute, and use imagesc:

    column_index = 4;
    imagesc(permute(Xc(:, column_index, :), [1 3 2]))
    

    enter image description here