如何有效地在matlab中创建这个矩阵?没有for循环?

时间:2015-07-28 11:07:00

标签: matlab vectorization

我想用这个函数创建一个N * N矩阵A:

enter image description here

其中x和y是N-d向量。我可以通过4嵌套for循环创建,但如何更有效地实现它?有没有for循环的方法吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

using element-wise .* operations will be dramatically faster than 4 nested for loops. I think you want something like this:

M = 100;
K = 100;
N = 40;
x = linspace(0,1,N);
y = linspace(0,1,N);

%order reversed matches i,j notation in question
[Y,X] = meshgrid(y,x);
A = zeros(size(X));

for m = 1:M
    for k = 1:K

        A = A + sqrt(m^2 + k^2)*sin(m*X).*cos(k*Y);

    end 
end