删除四个嵌套循环在Matlab [英] Removing four nested loops in Matlab
问题描述
我有以下四个嵌套循环在Matlab:
I have the following four nested loops in Matlab:
timesteps = 5;
inputsize = 10;
additionalinputsize = 3;
outputsize = 7;
input = randn(timesteps, inputsize);
additionalinput = randn(timesteps, additionalinputsize);
factor = randn(inputsize, additionalinputsize, outputsize);
output = zeros(timesteps,outputsize);
for t=1:timesteps
for i=1:inputsize
for o=1:outputsize
for a=1:additionalinputsize
output(t,o) = output(t,o) + factor(i,a,o) * input(t,i) * additionalinput(t,a);
end
end
end
end
有三种载体:一个输入向量,一个附加输入矢量和输出矢量。所有被连接的因素。每个向量在给定的时间步长值。我需要在每一个给定的时间步的所有组合输入,增加投入和因素的总和。后来,我需要从输出到输入来计算:
There are three vectors: One input vector, one additional input vector and an output vector. All the are connected by factors. Every vector has values at given timesteps. I need the sum of all combined inputs, additional inputs and factors at every given timestep. Later, I need to calculate from the output to the input:
result2 = zeros(timesteps,inputsize);
for t=1:timesteps
for i=1:inputsize
for o=1:outputsize
for a=1:additionalinputsize
result2(t,i) = result2(t,i) + factor(i,a,o) * output(t,o) * additionalinput(t,a);
end
end
end
end
在第三种情况下,我需要求和每一个时间步的所有三个向量的乘积:
In a third case, I need the product of all three vectors summed over every timestep:
product = zeros(inputsize,additionalinputsize,outputsize)
for t=1:timesteps
for i=1:inputsize
for o=1:outputsize
for a=1:additionalinputsize
product(i,a,o) = product(i,a,o) + input(t,i) * output(t,o) * additionalinput(t,a);
end
end
end
end
这两个code片段工作,但令人难以置信的慢。如何删除嵌套循环?
The two code snippets work but are incredibly slow. How can I remove the nested loops?
编辑:增加值,改变小事,所以片段是可执行
Added values and changed minor things so the snippets are executable
EDIT2:添加其他使用案例
Added other use case
推荐答案
第一部分
一个办法 -
t1 = bsxfun(@times,additionalinput,permute(input,[1 3 2]));
t2 = bsxfun(@times,t1,permute(factor,[4 2 1 3]));
t3 = permute(t2,[2 3 1 4]);
output = squeeze(sum(sum(t3)));
或轻微变种,以避免紧缩
-
Or a slight variant to avoid squeeze
-
t1 = bsxfun(@times,additionalinput,permute(input,[1 3 2]));
t2 = bsxfun(@times,t1,permute(factor,[4 2 1 3]));
t3 = permute(t2,[1 4 2 3]);
output = sum(sum(t3,3),4);
第二部分
t11 = bsxfun(@times,additionalinput,permute(output,[1 3 2]));
t22 = bsxfun(@times,permute(t11,[1 4 2 3]),permute(factor,[4 1 2 3]));
result2=sum(sum(t22,3),4);
第三部分
t11 = bsxfun(@times,permute(output,[4 3 2 1]),permute(additionalinput,[4 2 3 1]));
t22 = bsxfun(@times,permute(input,[2 4 3 1]),t11);
product = sum(t22,4);
这篇关于删除四个嵌套循环在Matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!