MATLAB: Help creating Z from X and Y for a contour plot

beginnercontourcontour plotplot

So I have values for X and Y in vector form (13 x 1) I need to generate matrix Z using those values to get a 13 x 13 matrix for my contour plot. So I want matlab to go calculate Z for every value of Y given a single value of X and so on.
figure(3)
force_amplitude=[1:13]'
force_time=[0:0.05:0.6]'
energy_consumption=20.093*12.5*((1.27/(force_amplitude*force_time))+force_time);
C=(1.27./(force_amplitude.*force_time))-force_time;
contour(force_amplitude,force_time,energy_consumption)

Best Answer

You need the invaluable assistance of the meshgrid function to make your dreams reality:
figure(3)
force_amplitude=1:13;
force_time=0:0.05:0.6;
[F_A, F_T] = meshgrid(force_amplitude, force_time);
energy_consumption = @(force_amplitude, force_time) 20.093*12.5*((1.27./(force_amplitude.*force_time))+force_time);
C = @(force_amplitude, force_time) (1.27./(force_amplitude.*force_time))-force_time;
contour(force_amplitude,force_time,energy_consumption(F_A, F_T))
xlabel('Force Amplitude')
ylabel('Force Time')
I created ‘energy_consumption’ (and ‘C’) as anonymous functions for convenience, then after vectorising them, called them from within your contour call. You can certainly create separate ‘Z’ matrices, for example:
Z = energy_consumption(F_A, F_T);
and then plot it.
If you are not already familiar with them, see the documentation on Anonymous Functions (link) for a full discussion.
In your code, you do not need the square brackets around the vectors, although if they make your code more readable for you, use them.