我无法让xi
和yi
范围包含除正整数值以外的任何内容,因为我将数据存储在矩阵中的方式(x和y值对应于它们的插槽)存储在),但我无法弄清楚这样做的更聪明的方法。有人可以帮帮我吗?我希望能够xi = -30:30
和yi = -30:30
。
function test3
f = @(x,y) y*sin(x) + sqrt(y);
function p
xi = 1:30;
yi = 1:30;
pts = zeros(size(xi,2),size(yi,2));
for x = xi
for y = yi
pts(x,y) = pts(x,y) + f(x,y);
end
end
surf(xi,yi,pts)
end
p
end
我正在处理的实际代码:
function Eplot(z, w, R, Psi)
ni = 0:2:4;
mi = 0;
xi = -30:30;
yi = -30:30;
pts = zeros(size(xi,2),size(yi,2));
for n = ni
for m = mi
for x = xi
for y = yi
pts(x,y) = pts(x,y) + utot(z, x/10^4, y/10^4, n, m, w, R, Psi);
end
end
end
end
surf(xi,yi,pts)
end
Eplot(zi, wi, Ri, Psii)
答案 0 :(得分:2)
使用meshgrid
(如surf
的文档中所述)并编写函数f
以使用逐个元素的操作,以便它可以进行矩阵输入。
f = @(x,y) y.*sin(x) + sqrt(y);
xi = -30:30;
yi = -30:30;
[x,y]=meshgrid(xi,yi);
surf(xi,yi,f(x,y))
(另外,我希望你真的不想为sqrt(y)
的负值绘制y
如果你不能以允许你给它向量参数的方式编写你的函数,那么你的for
循环是一个合理的方法,但我会这样写:
f = @(x,y) y.*sin(x) + sqrt(y);
xi = -30:30;
yi = -30:30;
pts=zeros(length(xi),length(yi));
for ii=1:length(xi)
for jj=1:length(yi)
pts(ii,jj)=f(xi(ii),yi(jj));
%// If `f` has more variables to iterate over (n, m, etc.) and sum,
%// do those loops inside the ii and jj loops
%// I think it makes the code easier to follow
end
end
surf(xi,yi,pts)