Search code examples
arraysmatlabbsxfunsimplification

Correct usage of arrayfun/bsxfun in Matlab - simple example


Assume we have a 1-d Matrix, with random length:

M = [102,4,12,6,8,3,4,65,23,43,111,4]

Moreover I have a vector with values that are linked to the index of M:

V = [1,5]

What i want is a simple code of:

counter = 1;
NewM = zeros(length(V)*3,1);
for i = 1:length(V)
    NewM(counter:(counter+2)) = M(V(i):(V(i)+2))
    counter = counter+3;
end

So, the result will be

NewM = [102,4,12,8,3,4]

In other words, I want the V to V+2 values from M in a new array. I'm pretty sure this can be done easier, but I'm struggeling with how to implement it in arrayfun /bsxfun...

bsxfun(@(x,y) x(y:(y+2)),M,V)

Solution

  • With bsxfun it's about getting the Vi on one dimension and the +0, +1 +2 on the other:

    M = [102,4,12,6,8,3,4,65,23,43,111,4];
    V = [1,5];
    NewM = M( bsxfun(@plus, V(:), 0:2) )
    
    NewM =
        102     4    12       
          8     3     4   
    

    Or if you want a line:

    NewM = reshape(NewM.', 1, [])
    
    NewM =
        102     4    12     8     3     4