trouble using quiver and contour plots.

4 views (last 30 days)
Nicole Hill
Nicole Hill on 26 Nov 2012
Here is a portion of my code:
dx=0.05;
dy=0.05;
im=41;
jm=21;
x=[-1:dx:1];
y=[0:dy:1];
for i=1:1:im
for j=1:1:jm
u(i,j)=2*y(j)*(1-x(i)^2);
v(i,j)=-2*x(i)*(1-y(j)^2);
psi(i,j)=x(i)^2-(x(i)^2)*y(j)^2+y(j)^2;
end
end
figure
axes('position',[.1 .3 .8 .6]);
contour(x,y,psi);
axes('position',[.1 .1 .8 .1]);
pcolor([0:100;0:100]);
figure
quiver(x,y,u,v);
I get the following error message for both plots: 'The size of X must match the size of Z or the number of columns of Z.'
Using the meshgrid function reverses the dimensions for some reason (it gives (21X41) for x and y when the actual size is x(41), y(21)). If I add this dimension by hand to get x and y of (41X21) and adding zeros to all other rows/columns, my plots are incorrect. Why don't the dimensions/assignment of (x,y,u,v) work for these plots?
I am clearly not understanding how the contour and quiver functions interpret the input.
Please help if you can. Thank you very much!

Answers (2)

Nicole Hill
Nicole Hill on 27 Nov 2012
Edited: Nicole Hill on 27 Nov 2012
I found that reversing the x and y vectors when calling meshgrid() solves the problem. I still do not understand what is going on here, but this seems to work.
[ypl,xpl] = meshgrid(y,x);
figure
contour(xpl,ypl,psi), hold on
quiver(xpl,ypl,u,v), hold off, axis image

Jonathan Epperl
Jonathan Epperl on 27 Nov 2012
Does this code achieve what you want:
dx=0.05;
dy=0.05;
x=[-1:dx:1];
y=[0:dy:1];
[X Y] = meshgrid(x,y);
P = X.^2 - (X.*Y).^2+Y.^2;
U = 2*Y.*(1-X.^2);
V = -2*X.*(1-Y.^2);
contour(X,Y,P); hold on;
quiver(X,Y,U,V);
hold off
colorbar
If yes, then some words of explanation:
  • The contour command expects 3 matrices of equal size from you, and will interpret it as the height at the point [X(i,j), Y(i,j)] being Z(i,j) for all i and j. In my version of Matlab, contour is even smart enough to make the x,y grid itself, and all that was missing in your code was a prime: contour(x,y,psi'); works, at least in 2012b.
  • quiver works similarly, and again only 2 primes were missing from your code
  • [X,Y] = meshgrid(x,y) generates the matrices such that X is constant along the 1st dimension (columns), and Y is constant along the 2nd dimension (rows). I don't think it matters, but your for-loop atrocity just happens to create the transpose of what's needed.
  • Lastly, is there a reason why you use pcolor and not colorbar? If so, tell us, I would be surprised if it wasn't easier to achieve what you want using the latter.

Categories

Find more on Vector Fields in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!