[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Vectorization question

From: Nicholas Jankowski
Subject: Re: Vectorization question
Date: Fri, 16 Oct 2015 12:44:41 -0400

On Fri, Oct 16, 2015 at 3:08 AM, Marco Cecconello <address@hidden> wrote:
Vectorization question: say I have a matrix A = (a11, a12; a21, a22) and
a vector B = (b1, b2, b3). I want to generate a matrix 2x2x3 C such that
C(:,:,i) = A + b(i). How can I do this without recurring to a for loop?
With repmat I can easily generate the 2 x 2 x 3 array containing copies
of A but how do I add b(i) to each (:,:,i)?

Octave uses broadcasting when there is a size mismatch between matrices.  (In matlab you use the bsxfun function)

you want the third dimension to be the projection for b, so first reshape b to be a dim3 vector, then do the addition:

>> A = [1 2;3 4];b = [5 6 7];
>> b=reshape(b,1,1,3)
b =

ans(:,:,1) =  5
ans(:,:,2) =  6
ans(:,:,3) =  7

>> A+b
ans =

ans(:,:,1) =

   6   7
   8   9

ans(:,:,2) =

    7    8
    9   10

ans(:,:,3) =

    8    9
   10   11

note you can also use reshape(b,1,1,[]) if you don't know the length of b, or you can use permute() to do the same thing.

Nick J.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]