Tuesday, July 24, 2012

3D plot and hold on in MATLAB

In MATLAB, plotting a number of 3D graphics objects in one graph relies on the function 'hold'. Execute the following in MATLAB:

figure, hold on,
plot3(rand(1,3),rand(1,3),rand(1,3)); 

The code is supposed to give you a 3D view, however, it gives you a 2D graph (2D view) instead. The reason is the call of 'hold on' freezes the view as 2D. To solve this issue, one way is to add 'view(3)' at the end, that is:

figure, hold on,
plot3(rand(1,3),rand(1,3),rand(1,3));
view(3)

Alternatively, call 'hold on' after you use the 3D plot function:

figure,
plot3(rand(1,3),rand(1,3),rand(1,3));
hold on;

These two methods will generate same results.