Help creating Z from X and Y for a contour plot

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)

 Risposta accettata

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.

2 Commenti

I think i just did that the hard way.
figure(3)
force_amplitude=[1:13];
force_time=[0:0.05:0.6];
for i=1:13;
E(i,:)=20.093*12.5*((1.27./(force_amplitude(:,i).*force_time))+force_time);
end
for i=1:13;
C(i,:)=((1.27./(force_amplitude(:,i).*force_time))-force_time);
end
E=transpose(E)
contour(force_amplitude,force_time,C,-0.4:0.2:1.2,'ShowText', 'on')
hold on
contour(force_amplitude,force_time,E,180:20:440,'ShowText', 'on')
hold off
Is this the long way of doing what meshgrid does?
In a word: Yes!
MATLAB has the ability to vectorise calculations, so taking advantage of that ability will save you much frustration, code complexity, and computational time.
See the documentation on Vectorization for an extended discussion.

Accedi per commentare.

Più risposte (0)

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by