Efficient way to split a vector into Matrix
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (2)
Andrei Bobrov
am 14 Apr. 2011
variant
D0 = buffer(B,5,4);
D = D0(2:end-1,4:end)
2 Kommentare
RoJo
am 14 Apr. 2011
Teja Muppirala
am 14 Apr. 2011
You learn something new every day...
Matt Fig
am 14 Apr. 2011
IDX = ones(3,5,'single');
IDX(:,1) = 1:3;
D = B(cumsum(IDX,2))
Or, to match your functional form:
function m_Array = MakeMatrixFast2(inputVector, inputLookbackPeriod, numPeriodsToCalculate)
IDX = ones(inputLookbackPeriod,numPeriodsToCalculate,'single');
IDX(:,1) = 1:inputLookbackPeriod;
m_Array = inputVector(cumsum(IDX,2));
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!