假设我有一个函数phi(x1,x2)=k1*x1+k2*x2,我已经在一个网格上计算过它,其中网格是一个正方形,在x1和x2轴上的边界分别为-100和100,步长为h=0.1。现在我想在我正在努力的网格上计算这个和:

我尝试的是:
clear all
close all
clc
D=1; h=0.1;
D1 = -100;
D2 = 100;
X = D1 : h : D2;
Y = D1 : h : D2;
[x1, x2] = meshgrid(X, Y);
k1=2;k2=2;
phi = k1.*x1 + k2.*x2;
figure(1)
surf(X,Y,phi)
m1=-500:500;
m2=-500:500;
[M1,M2,X1,X2]=ndgrid(m1,m2,X,Y)
sys=@(m1,m2,X,Y) (k1*h*m1+k2*h*m2).*exp((-([X Y]-h*[m1 m2]).^2)./(h^2*D))
sum1=sum(sys(M1,M2,X1,X2))Matlab说ndgrid中有错误,你知道我该怎么编码吗?
MATLAB显示:
Error using repmat
Requested 10001x1001x2001x2001 (298649.5GB) array exceeds maximum array size preference. Creation of arrays greater
than this limit may take a long time and cause MATLAB to become unresponsive. See array size limit or preference
panel for more information.
Error in ndgrid (line 72)
varargout{i} = repmat(x,s);
Error in new_try1 (line 16)
[M1,M2,X1,X2]=ndgrid(m1,m2,X,Y)发布于 2020-03-12 13:08:46
根据您的注释和代码判断,您似乎没有完全理解等式要求您计算的内容。
要获得某个给定(x1,x2)上的值M(x1,x2),您必须计算Z2上的和。当然,使用诸如MATLAB之类的数值工具箱,您只能在某个有限范围的Z2上进行计算。在本例中,由于(x1,x2)覆盖范围为-100,100 x -100,100和h=0.1,因此mh覆盖范围为- 1000,1000 x -1000,1000。示例:m= (-1000,-1000)给您mh = (-100,-100),这是您的域的左下角。所以,phi(mh)实际上就是所有离散点的φ(x1,x2)。
另外,由于您需要计算|x-hm|^2,因此可以将x = x1 + i x2视为复数来使用MATLAB的abs函数。如果您严格使用向量,则必须使用norm,这也是可以的,但会有点冗长。因此,对于某些给定的x=(x10, x20),您可以将整个离散平面上的x-hm计算为(x10 - x1) + i (x20 - x2)。
最后,您可以一次计算M的1个项:
D=1; h=0.1;
D1 = -100;
D2 = 100;
X = (D1 : h : D2); % X is in rows (dim 2)
Y = (D1 : h : D2)'; % Y is in columns (dim 1)
k1=2;k2=2;
phi = k1*X + k2*Y;
M = zeros(length(Y), length(X));
for j = 1:length(X)
for i = 1:length(Y)
% treat (x - hm) as a complex number
x_hm = (X(j)-X) + 1i*(Y(i)-Y); % this computes x-hm for all m
M(i,j) = 1/(pi*D) * sum(sum(phi .* exp(-abs(x_hm).^2/(h^2*D)), 1), 2);
end
end顺便说一句,这个计算需要相当长的时间。您可以考虑增加h、减少D1和D2,或者将这三项全部更改。
https://stackoverflow.com/questions/60630001
复制相似问题