Alex Azazel
Alex Azazel

Reputation: 342

How can I vectorize this loop in MATLAB?

I think this can be optimized by vectorization of the innermost loop.

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

Any ideas how to do that?

Upvotes: 0

Views: 52

Answers (1)

josoler
josoler

Reputation: 1423

You could replace your inner loop by something like this:

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(:);

Upvotes: 1

Related Questions