0

I have a vector v. I need to form an array a containing elements specified according to another array b. Each row in a (let's denote it by r) should contain all elements from v, with starting and ending indices corresponding to the first and last elements given in the matching column in b. For instance:

A(1, :) = v(b(1, 1):b(2, 1));
A(2, :) = v(b(1, 2):b(2, 2));
A(3, :) = v(b(1, 3):b(2, 3));

and so on. Obviously b(2,:) = b(1,:) + constant.

Can I do this without a loop in MATLAB?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
umayfindurself
  • 123
  • 3
  • 18

2 Answers2

1

Try this:

N=8; P=3; M=5;
v = rand(N,1);
b = zeros(2,M);
b(1,:) = [1 2 4 5 6];
b(2,:) = b(1,:) + P - 1;
A = cell2mat(arrayfun(@(i0,i1) v(i0:i1),b(1,:),b(2,:),'UniformOutput',false))'
chappjc
  • 30,359
  • 6
  • 75
  • 132
  • However, just to point out, as discussed [here](http://stackoverflow.com/questions/12522888/arrayfun-can-be-significantly-slower-than-an-explicit-loop-in-matlab-why), although loops take more space, they are faster. – umayfindurself Sep 30 '13 at 18:40
  • Out of curiosity, why did you need to do this without loops? – chappjc Sep 30 '13 at 18:51
  • @user2000581 Mind you that `bsxfun` is usually faster than both :) – Eitan T Oct 01 '13 at 05:57
1

You can use linear indexing and bsxfun to directly access the elements:

A = v(bsxfun(@plus, b(1,:).', 0:b(2,1)-b(1,1)));
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52