help-octave
[Top][All Lists]
Advanced

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

Re: n-dim product


From: Jaroslav Hajek
Subject: Re: n-dim product
Date: Wed, 30 Jul 2008 15:58:14 +0200

On Wed, Jul 30, 2008 at 3:18 PM, Francesco Potorti` <address@hidden> wrote:
> If I have two vectors and want to produce a matrix of all the possible
> products of their elements, I just multiply them:
>
> octave> x=1:3; y=1:4; x'*y
> ans =
>
>    1    2    3    4
>    2    4    6    8
>    3    6    9   12
>
> How to generalise this simple operation to multiple dimensions?
>
> I can do that like this:
>
> octave> m=shiftdim(1:3); n=1:4; z=shiftdim(1:2,-1);
> octave> repmat(m*n,[1,1,length(z)]) .* repmat(z,[length(m),length(n),1])
> ans =
>
> ans(:,:,1) =
>
>    1    2    3    4
>    2    4    6    8
>    3    6    9   12
>
> ans(:,:,2) =
>
>    2    4    6    8
>    4    8   12   16
>    6   12   18   24
>
> However, this involves creating a temporary matrix to multiply with
> element-by-element.  Moreover, it is difficult to read.
>
> Is this the most efficient way?
> Is this the simplest way?
>

the easy way:

[xx, yy, zz] = ndgrid (x, y, z);
xx .* yy .* zz

this may be faster:
reshape ((x'*y)(:) * z, [length(x), length(y), length(z)])

(x, y, z are row vectors)

> --
> Francesco Potortì (ricercatore)        Voice: +39 050 315 3058 (op.2111)
> ISTI - Area della ricerca CNR          Fax:   +39 050 315 2040
> via G. Moruzzi 1, I-56124 Pisa         Email: address@hidden
> (entrance 20, 1st floor, room C71)     Web:   http://fly.isti.cnr.it/
> _______________________________________________
> Help-octave mailing list
> address@hidden
> https://www.cae.wisc.edu/mailman/listinfo/help-octave
>



-- 
RNDr. Jaroslav Hajek
computing expert
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz



reply via email to

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