在 MATLAB 中编写向量和

Writing a vector sum in MATLAB

假设我有一个函数 phi(x1,x2)=k1*x1+k2*x2,我在一个网格上对其进行了评估,其中网格是一个正方形,在 x1x2 轴上的边界分别为 -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)

从您的评论和代码来看,您似乎没有完全理解方程式要求您计算的内容。

要在给定的 (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) 只是 phi(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、减少 D1D2,或者更改所有这三个。