在MATLAB中编写矢量和

问题描述 投票:0回答:1

假设我有一个函数phi(x1,x2)=k1*x1+k2*x2,该函数已在一个网格上进行了评估,其中该网格是一个正方形,在x1x2轴上的边界均为-100和100,步长为h=0.1。现在,我要在我正在努力挣扎的网格上计算此和:

enter image description here

我正在尝试的内容:

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)
performance matlab grid interpolation
1个回答
0
投票

从您的注释和代码来看,似乎您不完全了解方程式要求您进行计算。

要在给定的(x1,x2)处获得值M(x1,x2),必须在Z2上计算该总和。当然,使用诸如MATLAB之类的数字工具箱,您只能希望在Z2的有限范围内进行计算。在这种情况下,由于(x1,x2)覆盖范围[-100,100]×[-100,100],并且h = 0.1,因此,mh覆盖范围[-1000,1000]×[-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)

最后,您一次可以计算1个M项:

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或更改全部三个。

© www.soinside.com 2019 - 2024. All rights reserved.