MATLAB: Efficient way to split a vector into Matrix

for loopmatrix manipulationperformancevectorizing

Hi,
I am looking for an efficient way to do the following:
Take an input vector, e.g B = [2;5;8;11;3;6;9;15]
and return the array
D = [2 5 8 11 3;5 8 11 3 6;8 11 3 6 9]
, ie each column is a rolling subvector of B
My attempt below works but it causes a bottleneck in my programme. I have been trying to vectorize it but am finding it difficult.
If somebody has thoughts I would appreciate a pointer.
Thanks!
function ret = MakeMatrix(inputVector, inputLookbackPeriod, numPeriodsToCalculate)
m_Array = zeros(inputLookbackPeriod, numPeriodsToCalculate);
for i=1:numPeriodsToCalculate
m_Array(:,i) = inputVector(i:i+inputLookbackPeriod-1,1);
end
end

Best Answer

Here is an obscure way, using a Hilbert matrix. It is semi-coincidental that the indexing you need is exactly the (element-by-element inverse of the) Hilbert matrix.
For something less esoteric, you could probably use the filter command.
function m_Array = MakeMatrixFast(inputVector, inputLookbackPeriod, numPeriodsToCalculate)
H = 1./hilb(max(inputLookbackPeriod,numPeriodsToCalculate));
H = H(1:inputLookbackPeriod,1:numPeriodsToCalculate);
m_Array = inputVector(H);
end