Specifying view matrix to use for 3D plot

32 views (last 30 days)
Joshua
Joshua on 15 Dec 2023
Answered: Riya on 1 Feb 2024
Hello!
I am looking for a solution to the following problem. I can get the view matrix for some view of a 3D plot in Matlab using:
axis vis3d
M = view;
I would like to do the "inverse" of this code, i.e. specify a view matrix and set the view in the 3D plot to this matrix. How would I go about doing that? Unfortunately the view command takes view angles only and not a matrix, so it isn't as straightforward as view(M) and just the az/elev angle as parameters is an insufficient number of parameters. So how would one go about this best?
Thanks!

Answers (1)

Riya
Riya on 1 Feb 2024
In MATLAB, the view command indeed takes azimuth and elevation angles as parameters, which is a simplified way of setting the camera view for a 3D plot. However, if you have a full view matrix, you can set the camera properties directly on the axes object to reconstruct the desired view.
The view matrix M that you get from MATLAB is a 4x4 transformation matrix that includes rotation and translation, which sets the camera's position and orientation in the scene. To apply this matrix to a 3D plot, you need to set the CameraPosition’, ‘CameraTarget’, ‘CameraUpVector’, and ‘CameraViewAngleproperties of the axes object.
% Assuming you have a 4x4 view matrix M
% First, decompose the matrix to get the camera parameters
% Camera position is the last column of the first three rows
camPos = M(1:3, 4)';
% The camera target can be assumed at the origin (for simplicity)
% since the view matrix handles the relative position of the camera
camTarget = [0, 0, 0];
% The up vector is the second column of the first three rows
camUpVec = M(1:3, 2)';
% Set the camera parameters to the current axes
h = gca; % Get the handle to the current axes
set(h, 'CameraPosition', camPos, ...
'CameraTarget', camTarget, ...
'CameraUpVector', camUpVec);
% You might need to adjust the CameraViewAngle if necessary
% set(h, 'CameraViewAngle', yourDesiredViewAngle);
Please note that the actual camera target in your scene might not be the origin [0, 0, 0]. You may need to adjustcamTargetaccordingly if you know the point that the camera should be looking at.
For more information you can refer following article:

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!