有没有办法向量化这个matlab嵌入的for循环代码?
我有一个带有嵌套 for
循环的代码
for a = 1:P
for i = 1:p
for j = 1:p
A(C(a, i), C(a, j)) = A(C(a, i), C(a, j)) + M(i, j);
end
end
end
,我设法改善了时间复杂度
i = 1:p;
j = 1:p;
for a = 1:P
A(C(a, i), C(a, j)) = A(C(a, i), C(a, j)) + M(i, j);
end
但是,由于数组维度错误,我无法对最后一个 for
循环使用相同的方法。常量 P
也明显大于 p
,这使得第一个 for
循环成为最需要优化的部分。
如何矢量化最后一个循环?
作为任意值的示例:
p = 2;
P = 5;
A = sparse(P+1, P+1); % A is a 6x6 matrix here. Sparse since we do not expect many non-zeros
C = [1 3; 3 5; 5 2; 2 4; 4 6]; % Pxp matrix with largest term = P+1
M = [3 6; 8 3]; % pxp matrix
for 循环的结果应该是:
A(C(1, 1:2), C(1, 1:2)) += M(1:2, 1:2);
A(C(2, 1:2), C(2, 1:2)) += M(1:2, 1:2);
.
.
.
A(C(5, 1:2), C(5, 1:2)) += M(1:2, 1:2);
I had a code with nested for
-loops
for a = 1:P
for i = 1:p
for j = 1:p
A(C(a, i), C(a, j)) = A(C(a, i), C(a, j)) + M(i, j);
end
end
end
I managed to ameliorate the time complexity
i = 1:p;
j = 1:p;
for a = 1:P
A(C(a, i), C(a, j)) = A(C(a, i), C(a, j)) + M(i, j);
end
However, I cannot use the same method for the last for
loop because of array dimension errors. The constant P
is also significantly larger than p
, which makes the first for
loop the most important to optimize.
How can I vectorise the last loop?
As an example of arbitrary values:
p = 2;
P = 5;
A = sparse(P+1, P+1); % A is a 6x6 matrix here. Sparse since we do not expect many non-zeros
C = [1 3; 3 5; 5 2; 2 4; 4 6]; % Pxp matrix with largest term = P+1
M = [3 6; 8 3]; % pxp matrix
The result of the for loop should be:
A(C(1, 1:2), C(1, 1:2)) += M(1:2, 1:2);
A(C(2, 1:2), C(2, 1:2)) += M(1:2, 1:2);
.
.
.
A(C(5, 1:2), C(5, 1:2)) += M(1:2, 1:2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是矢量化形式:
但是,它的内存/处理器效率可能低于循环。由于
P
大于p
,您只能对外部循环进行向量化:如果计算应应用于密集数组,请使用
accumarray
:Here is a vectorized form:
However it may be less memory/processor efficient than the loop. As
P
is larger thanp
, You can only vectorize the outer loop:Use
accumarray
if the computations should be applied on dense array: