help-octave
[Top][All Lists]

Re: Vectorization quiz

 From: Daniel Arteaga Subject: Re: Vectorization quiz Date: Thu, 28 Apr 2011 17:58:08 +0200 User-agent: Mozilla/5.0 (X11; U; Linux i686; ca-ES; rv:1.9.2.14) Gecko/20110223 Thunderbird/3.1.8

```Al 21/04/11 16:37, En/na James Sherman Jr. ha escrit:
```
```On Thu, Apr 21, 2011 at 4:49 AM, Daniel Arteaga

Hi,

How could I vectorize the following piece of code?

P = zeros(size(fInf));
for i = 1:length(fInf)
P(i) = sum( S2( fLin > fInf(i) & fLin < fSup(i) ) );
endfor

where

fInf is a vector of length 1000
fSup is a vector of length 1000
P    is a vector of length 1000
S2   is a vector of length 50000
fLin is a vector of length 50000

Thank you very much in advance,

Daniel

_______________________________________________
Help-octave mailing list
https://mailman.cae.wisc.edu/listinfo/help-octave

Well, I'm not saying that this is the best way, but you could try this:

n = length(fInf);
m = length(fLin);

fLin_repeated = repmat(fLin, [1, n]);
S2_repeated = repmat(S2, [1, n]);
fInf_repeated = repmat(fInf', [m, 1]);
fSup_repeated = repmat(fSup', [m, 1]);

tmp1 = (fLin_repeated > fInf_repeated) & (fLin_repeated < fSup_repeated);
P = sum( S2_repeated .* tmp1 )';

I particularly don't like the last line.  I feel like there is a
but for the life of me I can't remember what it is.  The downside is
that you will have 4 different 50000 by 1000 matrices, which may or may
not be problematic.
```
```
```
Thank you very much for your answer. It comes down that I'm somewhat memory-limited, so it is not very convenient to have such big matrices. Maybe particioning S2 in smaller chunks as you suggest we could get a good compromise between memory consumption and speed.
```

```