如何在MATLAB中对此循环进行矢量化?

时间:2015-08-01 13:40:56

标签: matlab optimization multidimensional-array matrix-multiplication

我认为这可以通过最内层循环的矢量化来优化。

input = 2*rand(24,24,3)-1;
theta = 2*rand(26,12,3)-1;

output = zeros(20,20,12); % preallocating
temp = zeros(3,12); % preallocating
for i = 1:20
    for j = 1:20
        for c = 1:3
            temp(c,:) = [1, reshape(input(i:i+4,j:j+4,c),1,25)]*theta(:,:,c);
        end
        output(i,j,:) = sum(temp);
    end
end

任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式替换内部循环:

aux = [ones(1,3); reshape(input(i:i+4,j:j+4,:),25,3)];
theta_concat = reshape(permute(theta, [2 1 3]),12,78);
output(i,j,:) = theta_concat*aux(:);