Cannot calculate gradient of contour plot

조회 수: 22 (최근 30일)
KostasK
KostasK 2020년 9월 24일
댓글: KostasK 2020년 9월 24일
Hi all,
I am currently attempting to draw a quiver plot on top of a contour plot, such that I can see the gradient of the contour function. However for some reason the gradient calculation does not take place correctly as all the quivers are far from being perpendicuar to the contours. This suprises me as the task itself is pretty simple and I have managed to accomplish it with mock data, see here:
clear ; clc
% Grid matrices
x = -2:0.25:2;
y = x;
[X,Y] = meshgrid(x);
% Function Matrix
F = X.*exp(-X.^2-Y.^2);
% Calculate Gradient
[FU, FV] = gradient(F, diff(x(1:2))) ;
% Plot
figure
hold on
contour(X, Y, F)
quiver(X, Y, FU, FV)
However, using my own data (you can find them attached its a simple 30x30 matrix), the same process does not seem to accomplish the task:
clear ; clc
% Grid matrices
x = linspace(-0.1, 0.1, 30) ;
y = linspace(8, 12, 30) ;
[X, Y] = meshgrid(x, y) ;
% Function Matrix
load('my_data.mat')
% Calculate Gradient
[FU, FV] = gradient(F, diff(x(1:2)), diff(y(1:2))) ;
% Plot
figure
hold on
contour(X, Y, F)
quiver(X, Y, FU, FV)
The weird thing is that the countour plot gets generated correctly, however something is off with the quiver. Even when I scale down the quiver vectors to say 0.2, they don't have the correct orientation relative to the contours.
Thanks for your help in advance
  댓글 수: 2
KSSV
KSSV 2020년 9월 24일
How did you generate that F?
KostasK
KostasK 2020년 9월 24일
편집: KostasK 2020년 9월 24일
Its a fairly complex process of generating F, that's why I have attached it as a .mat file. I assumed that it shouldn't matter how F is generated, but rather that it forms a good contour plot.

댓글을 달려면 로그인하십시오.

채택된 답변

Bjorn Gustavsson
Bjorn Gustavsson 2020년 9월 24일
If you modify your call to gradient to:
[FU, FV] = gradient(F, diff(y(1:2)), diff(x(1:2)));
You get a more reasonable set of quivers:
contour(X, Y, F)
hold on
quiver(X(1:2:end,1:2:end), Y(1:2:end,1:2:end), FU(1:2:end,1:2:end)/2, FV(1:2:end,1:2:end)/2,0)
The zero is to turn off the automatic scaling in quiver.
HTH
  댓글 수: 1
KostasK
KostasK 2020년 9월 24일
Yes, it appears that scaling is the issue here. Because when I use axis equal even though the contour is greately distorted and inneligible, the gradient appears to be correct. So your answer works for me.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Vector Fields에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by