how to get parts of a vector and store it as a matrix without using loops

I got a vector and I would like to transform certain parts of this vector into a new matrix without using loops. e.g. vector v=[1;2;3;4;5;6;7;8;9] and I would like to get the 4th and the 8th entry plus the two entrys before. from v=[1;2;3;4;5;6;7;8;9] to result=[2,3,4;6,7,8]
I tried to do it like this but it gets me only the first row of the result matrix
i=[4;8] result=v(i:i-2)
Any help is appreciated! Thanks

Answers (1)

Hi,
the simple and readable way:
[v(i-2) v(i-1) v(i)]
and here a more complex solution:
v = (1:9)';
i = [4; 8];
v(bsxfun(@minus, i, repmat(2:-1:0, length(i), 1)))
Titus

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Asked:

on 6 Dec 2011

Community Treasure Hunt

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

Start Hunting!