trouble using quiver and contour plots.

조회 수: 4 (최근 30일)
Nicole Hill
Nicole Hill 2012년 11월 26일
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!

답변 (2개)

Nicole Hill
Nicole Hill 2012년 11월 27일
편집: Nicole Hill 2012년 11월 27일
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 2012년 11월 27일
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.

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by