简体   繁体   English

有没有办法向量化这个 matlab for 循环?

[英]Is there a way to vectorize this matlab for loop?

for i = 2:N
    A(i,i-1:i+1) = [1, -2, 1];
end

Hello, matlab is telling me that this code can be faster by using spalloc for the matrix A (which I have) but also by vectorizing this for loop.您好,matlab 告诉我,通过对矩阵 A(我有)使用 spalloc 以及通过矢量化此 for 循环,这段代码可以更快。 I've tried to use the following:我尝试使用以下内容:

i = 2:N
A(i, i-1:i+1)

but the result obviously turned out to be not what I want.但结果显然不是我想要的。

How can I solve this?我该如何解决这个问题?

Thank you!谢谢!

It looks like you're trying to get a second-order difference operator, except your loop winds up missing the first row and including an extra column.看起来您正在尝试获得二阶差分运算符,除了您的循环最终缺少第一行并包含一个额外的列。 The normal (sparse) difference operator is generated like this:普通(稀疏)差分算子是这样生成的:

N = 10;
v = ones(N, 1);
A = spdiags([v -2*v v], [-1 0 1], N, N);
full(A)  % for display only

You'll see:你会看到的:

ans =
    -2     1     0     0     0     0     0     0     0     0
     1    -2     1     0     0     0     0     0     0     0
     0     1    -2     1     0     0     0     0     0     0
     0     0     1    -2     1     0     0     0     0     0
     0     0     0     1    -2     1     0     0     0     0
     0     0     0     0     1    -2     1     0     0     0
     0     0     0     0     0     1    -2     1     0     0
     0     0     0     0     0     0     1    -2     1     0
     0     0     0     0     0     0     0     1    -2     1
     0     0     0     0     0     0     0     0     1    -2

If that's not quite what you want (eg, you really don't want the first row), then it's probably faster to generate it as above and then fix it up.如果这不是您想要的(例如,您真的不想要第一行),那么像上面那样生成它然后修复它可能会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM