figure view direction issue

1 回表示 (過去 30 日間)
Brendan Clark
Brendan Clark 2021 年 4 月 16 日
コメント済み: DGM 2021 年 4 月 16 日
I just need to view figure 2 from the same direction as figure 1, I used the same view commands for both figures but for some reason it only worked for figure 1
clear variables
clc
x=-3*pi:.2:3*pi;
y=-3*pi:.2:3*pi;
for i = 1:length(x)
for j = 1:length(y)
z(i,j)=exp(-(abs(y(j)/7))).*sin(x(i))+exp(-(abs(x(i)/7)))*cos(y(j));
end
end
[X,Y] = meshgrid(x,y);
Z=exp(-(abs(Y/7))).*sin(X)+exp(-(abs(X/7))).*cos(Y);
AZ = -40;
EL = 30;
figure (1)
surfc(x,y,z)
zlim([-1,1.8])
xlabel('x')
ylabel('y')
zlabel('z')
title('z=exp(-|y/7|)sin(x) +exp(-|x/7|))cos(y);')
set(gca, 'XTick', [-5,0,5])
set(gca, 'YTick', [-5,0,5])
colorbar
view(AZ, EL)
figure (2)
surfc(X,Y,Z)
zlim([-1,1.8])
xlabel('x')
ylabel('y')
zlabel('z')
title('z=exp(-|y/7|)sin(x) +exp(-|x/7|))cos(y);')
set(gca, 'XTick', [-5,0,5])
set(gca, 'YTick', [-5,0,5])
colorbar
view(AZ, EL)

採用された回答

DGM
DGM 2021 年 4 月 16 日
The problem you're having is improper correspondence between your axes. I think you're presuming that the loop is a known good example, but it's not. This loop:
for i = 1:length(x)
for j = 1:length(y)
z(i,j)=exp(-(abs(y(j)/7))).*sin(x(i))+exp(-(abs(x(i)/7)))*cos(y(j));
end
end
produces Z data that's transposed WRT x and y. The only reason this doesn't throw an error is because x and y have the same length. If you change y to say
y=-6*pi:.2:6*pi;
then you'll get a nice error because x,y, and z have mismatched geometry.
Error using surf (line 71)
Data dimensions must agree.
If instead you use
z(j,i)=exp(-(abs(y(j)/7))).*sin(x(i))+exp(-(abs(x(i)/7)))*cos(y(j)); % note LHS subscript positions
the plots will work without error, the two versions will match, and the x and y orientation matches the axis labels.
FWIW, i'm assuming the only reason you're making two identical plots is to try different methods of generating the Z data. While it's often more convenient to use meshgrid, it can also be done with the x,y vectors themselves.
z=exp(-abs(y'/7)).*sin(x)+exp(-(abs(x/7))).*cos(y');
This is elementwise operations using one row vector and one column vector. This works by generalized implicit array expansion post-R2016b. Prior to that, the same could be done using bsxfun().
  2 件のコメント
Brendan Clark
Brendan Clark 2021 年 4 月 16 日
That did face both of the figures in the same direction, however, figure one already faced the correct way in this scenario, and your correction changed them both to the direction of figure 2. However, fortunately, your explanation is fantastic and was detailed enough that I was able to find a slightly different correction that has them both facing the right way, thank you!
DGM
DGM 2021 年 4 月 16 日
Glad to hear it

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGreen についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by