Search code examples
matlabgraphmatlab-figure

How to plot a polynomial with two variables as a surface in MATLAB?


I have tried plotting this equation in MATLAB:

0.9486 - (1.0544*w0) + (0.8961*w1) + (w0*w1) + 1.1*(w0^2+w1^2)

The values of w0 are from 0 to 4 and w1 is from -4 to 0

I need to plot this as a surface in MATLAB so i wrote the following code:

w0=(0:0.2:4); % y-axis
w1=(0:-0.2:-4); % x-axis

J=zeros(length(w0),length(w1)); % Matrix to be plotted on z-axis as a 
surface

i=0; % indices for creating J
j=0; % indices for creating J

for w0=0:0.2:4
   j=j+1;
   i=i+1;
    for w1=0:-0.2:-4
           J(i,j)=0.9486-1.0544*w0+0.8961*w1+w0.*w1+1.1*(w0.*w0+w1.*w1);
           % Equation to be implemented 
    end
end
w0=(0:0.2:4); 
w1=(0:-0.2:-4);
%w0 and w1 created again as for loops reduced them to their 
final value of 4 and -4.


mesh(w1,w0,J) %to create surface plot

ax = gca;
ax.XDir = 'reverse'; %reversing the axis as required in the task

While the surface is created, however the matrix J isn't accurately filled. It is indeed 21x21 as it should be (w0 and w1 are both 1x21 vectors), but the values in J only appear at the diagonal, rest are zero.

I cannot have w0 and w1 as indices as they include decimals and having i and j as indices like this (after the first for loop) is the only way I can get a 21x21 matrix size for J.

This is the image of the required surface:

enter image description here

This is the image of the surface I have been able to plot so far:

enter image description here

Can anyone help me in filling the J matrix correctly so I can re-create the correct surface?


Solution

  • I haven't looked at your code in detail, but

    Here's how I would do it. This makes use of implicit singleton expansion, which requires Matlab R2016b or later:

    w0=(0:0.2:4).'; % y-axis
    w1=(0:-0.2:-4); % x-axis
    J = 0.9486 - (1.0544.*w0) + (0.8961.*w1) + (w0.*w1) + 1.1*(w0.^2+w1.^2);
    mesh(w1,w0,J)
    xlabel w1
    ylabel w0
    ax = gca;
    ax.XDir = 'reverse';
    

    enter image description here