vectorization

Ben Abbott bpabbott at mac.com
Wed Jul 16 20:17:22 CDT 2008


On Jul 16, 2008, at 7:01 PM, David Bateman wrote:

> David Bateman wrote:
>> The final reshape should use size(a) and not size(A).. Thus the code
>>
>> function q = newfilter1 (A, npoints)
>>
>> % assumes A is a muliple of npoints long
>> a = reshape (A, npoints, numel(A) / npoints);
>> q = reshape (repmat (min (abs(A - repmat(mean (A, 1), npoints, 1)),
>> 1),  npoints, 1), size (a));
>>
>> endfunction
>>
>> should be used instead. Untested as is the previous code.
>>
>> D.
>>
> Sorry take 3.
>
> function q = newfilter (A, npoints)
>
>  % assumes A is a muliple of npoints long
>  a = reshape (A, npoints, numel(A) / npoints);
>  [dum, idx] = min (abs(a - repmat(mean (a, 1), npoints, 1)), [], 1)
>  q = reshape (repmat (a(idx + [0 : numel(A) / npoints - 1] * ...
>             npoints), npoints, 1), size (A));
>
> endfunction
>
> Bit hard to test the code at the moment due to lack of a copy of  
> Octave,
> which explains the number of attempts to get it right
>

I took a look at this as well and would have responded earlier but my  
internet went down during a thunderstorm :-(

David, of the three versions you posted only the third ran for me  
without error. While the 3rd version does run, it does not give (what  
I think) is the correct answer :-(

octave:46> A = rand([1,9])
A =

    0.90785   0.89152   0.74896   0.71078   0.21859   0.26943    
0.89706   0.63350   0.47987

octave:47> q = newfilter (A, 3)
q =

    0.89152   0.89152   0.89152   0.26943   0.26943   0.26943    
0.63350   0.63350   0.63350

Unfortunately, a quick check of the first 3 elements gives a incorrect  
result.

octave:48> mean (A(1:3))
ans =  0.84944

The repmat approach had not occurred to me. The approach I took was  
to ...

       a = mean (reshape(A, [npoints, numel(A)/npoints]));
       q = reshape (ones (npoints, 1) * a, [1, numel(A)]);

Which (I believe) produces the desired result.

octave:49> q = newfilter (A, 3)
q =

    0.84944   0.84944   0.84944   0.39960   0.39960   0.39960    
0.67014   0.67014   0.67014

Ben


More information about the Help-octave mailing list