how to create a matrix when using surf function?

I want to solve this problem:
figure(1);
[u,v]=meshgrid(-40:1:40);
D1=sqrt((u-40)^2+v^2);
D2=sqrt((u+40)^2+v^2);
if (D1<=40)&(D2<=40)
F=0;
else
F=1;
end
surf(u,v,F);
shading interp;
however, in this way, matlab tells me ''
错误使用 surf (line 71)
Z 必须为矩阵,不能是标量或向量。''
how can I use surf correctly?

回答(1 个)

What you are doing there is making F a scalar, but F needs to be a matrix the same size as u and v, so something like this:
F = ones(size(u));
F(D1 <= 40 & D2 <= 40) = 0;
Here logical indexing is used to set the value of F based on conditions involving D1 and D2.

1 个评论

Thank you for you help. "F needs to be a matrix the same size as u and v" is really helpful. However, when I use this code:
F(D1 <= 40 & D2 <= 40) = 0;
I find it does not work.
So I change it this way.
figure(1);
[u,v]=meshgrid(-80:1:80);
F = ones(size(u));
for j=1:160
for i=1:160
D1=sqrt((i-80-40)^2+(j-80)^2);
D2=sqrt((i-80+40)^2+(j-80)^2);
if (D1<=80 & D2<=80)
F(i,j)=0;
else
F(i,j)=1;
end
end
end
surf(u,v,F);
shading interp;
and the result is shown in figure. But I think there is a better way to realize it especially for the part of "i j". Can you give me some advice.

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 图形性能 的更多信息

产品

版本

R2020a

提问:

2022-1-18

评论:

2022-1-20

Community Treasure Hunt

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

Start Hunting!