Widgetaah
Widgetaah

Reputation: 31

Using a diagonal values in a square matrix? to avoid loop

I have 2 (1 x n) matrices that I want to multiply each element together, n number of times, shifting the second matrix 1 step each time.

This code works fine, but I'm wondering if a better way with (n by n) matrix, values on the diagonals and no 'for loop' would be faster (more elegant) ?

y = [];
for i=[1:length(x1)]
    x2 = circshift(x2,[0,1]);
    y(i) = sum(x1 .* x2);
end;

Upvotes: 1

Views: 78

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You can use convolution to obtain the same result as your code:

y = conv(x1, fliplr([x2 x2]), 'same');

Upvotes: 2

Related Questions