help-octave
[Top][All Lists]
Advanced

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

Re: vectorization help


From: Jordi Gutiérrez Hermoso
Subject: Re: vectorization help
Date: Mon, 3 Oct 2011 13:54:27 -0500

On 3 October 2011 12:26, William Krekeler <address@hidden> wrote:
> % original code set
>
> RC = rand( 1, 448 );
>
> Cube = rand( 160,512,448 );
>
> tic
>
> for lamda = 1: size( Cube, 3 )
>
>    Cube(:,:,lamda) = ( RC(lamda)./ squeeze( Cube(:,:,lamda) ) );
>
> end
>
> toc

You want to divide each element of the RC vector by each matrix in the
Cube array. This is a prime example of broadcasting with bsxfun:

    Cube = bsxfun(@rdivide, permute(RC, [1, 3, 2]), Cube);

Note that in the current development branch and very likely in the
future 3.6 release, this can simply be written this way (and it's
slightly faster too):

    Cube = permute(RC, [1, 3, 2]) ./ Cube;

You need the call to permute (generalised n-dimensional transpose) in
order to properly align the dimensions of RC with those of Cube. The
following document from Numpy explains this broadcasting best:

    http://www.scipy.org/EricsBroadcastingDoc

You can skim that document if you are unfamiliar with numpy (they use
0-based indexing instead of 1-based). The important information there
is the block diagrams that explain broadcasting. Also observe how you
were already using a limited form of broadcasting, by doing scalar ./
matrix. Broadcasting can be more general than that.

HTH,
- Jordi G. H.


reply via email to

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