>> x=0:0.001:720;
>> y=sind(x);
>> z=cosd(x);
>> surf(x,y,z);
I want to plot a surface using the above code i.e. x in X-axis, y is Y-axis, and z in Z-axis. I also programmed a FORTRAN code for the following purpose, created a csv file, and plotted it in origin. I am getting a result as this:
However, in MATLAB, I am getting a similar idea when using:-
>> plot3(x,y,z)
as in this image:
but it's not a surface (for obvious reasons).
When using the surf
command, I am also getting an error saying:
Z
must be a matrix, not a scalar or vector.
What could be the possible problem with my code?
Using surf
requires Z
to be a matrix. This is fixed easily with functions like meshgrid
(also useful is griddata
).
Using meshgrid
makes using surf
very accessible.
But both Z
and Y
are just functions of X
so I'm unable to explain why your plot Z
-value would change with both X
and Y
. From the analytical (mathematical) equations you've listed, the Z
-value should be constant in the Y
-dimension.
stepsize = 1; % use 10 for cleaner look
x = 0:stepsize:720;
y = sind(x);
[X,Y] = meshgrid(x,y);
Z = cosd(X);
surf(X,Y,Z)
Notice that the contour lines are straight & parallel in the Y
dimension (using surfc(X,Y,Z)
).
Another method is to loop through elements of x
(indexed by i
) and y
(indexed by j
) where both x
and y
(vectors) to calculate Z(i,j)
where Z
is a matrix. Due to default assignment for rows & columns, this method requires transposing the Z
matrix such as surf(X,Y,Z.')
.
Related Posts:
How can I plot a function with two variables in octave or matlab?
MATLAB plot part of surface