Special matrix without for loop (vectorizing loop)

Hi Guys
I am trying to improve a performance of a code which develops a special matrix. This matrix looks really simple but I couldn't find a solution to develop it without a for loop. This is a huge matrix and a for loop causes the code takes hours to run.
imagine a vector A = [ 1; 2; 3; 4; 5; 6; 7 ] I want to develop matrix B based on A. numbers are indexes not real numbers.
B = [1 2 3 4; 2 3 4 5; 3 4 5 6; 4 5 6 7 ]
your help is really appreciated.
Regards Mitch

 Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 3 de Sept. de 2011
variant 1
B = hankel(A(1:4),A(4:end))
variant 2
B1 = cumsum([A(1:4) ones(4,3)],2)
variant 3
B2 = bsxfun(@plus,A(1:4),[0 1:3])

4 comentarios

M
M el 3 de Sept. de 2011
Wow
Saved me hips of time
Thanks :)
Oleg Komarov
Oleg Komarov el 3 de Sept. de 2011
If you think that this answer soved your problem, please accept it.
M
M el 5 de Sept. de 2011
about variant 2 3 they are good when the numbers are integers like 1 2 3 4 5 6 ... but the numbers are just indexes of my matrix not real numbers. So I think only Hankel is working properly. I developed my code again based on Hankel and I noticed the Hankle even deteriorates the speed of code in comparison to normal for-loop code. I am talking doing the same Hankle function on a vector with 200,000 elements for 1000 times.
hankel
Hankel matrix
Syntax
H = hankel(c)
H = hankel(c,r)
in which my c has 150 elements.
Oleg Komarov
Oleg Komarov el 5 de Sept. de 2011
Fo variants 2 and 3 then use A(B1), A(B2);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

M
M
el 3 de Sept. de 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by