Suri
Suri

Reputation: 209

Plotting a Matrix in 3D space in MATLAB without using mesh and surf type of plots

I am not familiar with MATLAB environment and I want to draw a matrix in a way that presents each cell of a matrix as a point in the 3D space.

For example present matrix "A " with the following points in 3D space: x=1, y=1 Z= 10 , x=1, y=3 Z=27 until reach the point x=3, y=3, z=26.

 A =
    10    15    27
    56    87     2
    90    87    26

I do not want to use mesh and surf. I am looking for diagram like plot3 digram.I tried plot3 but it does not show the value of z correctly.

i=1:3;
j=1:3;
plot3(i,j,A(i,j))

enter image description here

In the above figure; 3 values are presented for when x=3 and y=3 however it should present these values for x=1,y=3; x=2,y=3;x=3,y=3

Upvotes: 2

Views: 761

Answers (2)

Hoki
Hoki

Reputation: 11812

To begin I would recommend you to change your variable names. I'll use x and y instead of i and j. In many language these symbols are more typically used for scalar index rather than full vector indices, and in Matlab they can have a special significance (they are used to represent complex numbers).

That said, in your statement i=1:3; you only generate 3 indices, but you have 9 values to plot in your matrix. These 3 indices have to be repeated (3 times in your case, one for each column). So a proper x and y generation would be:

%% // Manual mesh/coordinate generation
x = bsxfun(@times,1:size(A,1), ones([size(A,2) 1])) ;
x = x(:) ;

y = bsxfun(@times, ones([1 size(A,1)]) , (1:size(A,2)).' )  ;
y = y(:) ;

With that you can use at your convenience scatter3 or plot3:

hscat = scatter3( x, y, A(:) ) ;
hp3 = plot3( x, y, A(:),'Marker','o','LineStyle','none') ;
%// will both produce exactly the same result

Now please consider the fact that the way I generated the x and y coordinate is nothing more than what meshgrid would do for you (or the more dimension generic ndgrid).

For example, in the code below, the 3 plotting methods will produce exactly the same ouput than above, so just take your pick:

%% define a grid
[X,Y] = meshgrid( 1:size(A,1) , 1:size(A,2) ) ;

%% // surface plot (but only points visible, no line)
hsurf = surf(X,Y,A,'Marker','o','LineStyle','none','FaceColor','none') ;

%% // scatter3
hscat = scatter3( X(:), Y(:), A(:) ) ;

%% // plot3
hp3 = plot3( X(:), Y(:), A(:),'Marker','o','LineStyle','none') ;

Why reinvent the wheel when you have one at hand ... meshgrid do the job for you in less code instruction ;-)

Upvotes: 3

beaker
beaker

Reputation: 16821

To generate the coordinates, you should use ndgrid (or meshgrid, which swaps X and Y.):

[X, Y] = ndgrid(1:3, 1:3);

plot3 is going to connect the input points with a line, so if you want distinct points in your plot, use scatter3:

scatter3(X(:), Y(:), A(:));

(You can also use plot3 in the same way if you want the lines.)

Upvotes: 0

Related Questions