How to plot values of a variable Z on an arbitrary 2D path in X and Y

조회 수: 7 (최근 30일)
Hello,
What I would like to do is basically to plot values of a matrix Z along a path defined by points {(X1,Y1); (X2,Y2)} inside its domain.
if we take as an example this code from the meshgrid command examples:
x = -2:0.25:2;
y = x;
[X,Y] = meshgrid(x);
F = X.*exp(-X.^2-Y.^2);
surf(X,Y,F)
What I would like to do is to make a 2D plot of the values of Z along a straight path line defined by two points. the next picture gives an idea of the path seen from the top.
In my case the values of Z are not calculated from an explicit formula but are numerical results forma nother code, and they have been interpolated using the function griddata, since I only had vectors before.
Thank you for the help!

채택된 답변

Cris LaPierre
Cris LaPierre 2020년 11월 17일
Since you have the equation, just create vertors for X and Y of the line, then solve for Z using those values.
Assuming that's not necessarily the case all the time, you could also use interp2 to interpolate the values of Z along the line using the known gridded data, as well as the X and Y values of the line.
x = -2:0.25:2;
y = x;
[X,Y] = meshgrid(x);
F = X.*exp(-X.^2-Y.^2);
surf(X,Y,F)
view(2)
% Define an arbitrary straight-line path
hold on
plot3([-1.5 -0.1],[1.75 -1.7],[1 1],'r-o','LineWidth',3)
hold off
% Use interp2 with X and Y vectors of the line to solve for z
xq=linspace(-1.5,-0.1,15);
yq=linspace(1.75,-1.7,15);
vq=interp2(X,Y,F,xq,yq);
figure
plot(vq)
  댓글 수: 1
Gianluca Vernassa
Gianluca Vernassa 2020년 11월 17일
Ok great thank you! That was blind fast! I'm astonished.
Interp2 is doing the job perfectly, and indeed in my case I had numerical data coming from a finite element code, so there was no direct formula. My apologies if it wasn't clear.
Thank you very much.
Gianluca

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by