open water
open water

Reputation: 127

creating this matrix in matlab

Given

A=[a_1 a_2 a_3 ... a_n]

How to make this?

[a1 ... a100]
[a2 ... a101]
...
[an-100+1 ... an]

I want to not use for-loop here since I want to speed it up. Thank you.

Upvotes: 0

Views: 47

Answers (1)

knedlsepp
knedlsepp

Reputation: 6084

You can use:

n = numel(A);
m = 100;
I = bsxfun(@plus, 1:m, (0:n-m).');
B = A(I);

As a sidenote: The for loop doesn't perform that bad:

B = zeros(n-m+1, m);
for i = 1:size(B)
    B(i,:) = A(i:i+m-1);
end

As far as my testing goes, it is slower only by a factor of 4 and this calculation should hardly be a bottleneck in your program anyway.

Upvotes: 4

Related Questions