How do I replace this for-loop?

Francesco Potorti` Potorti at isti.cnr.it
Sun Jul 6 04:33:20 CDT 2008


>Given an array, n, of datapoints, such that:
>
>>> size(n)
>rows = 27000
>columns = 2
>
>where n(:,1) are all the integer x values, and n(:,2) are all the
>integer y values, both integer values are in the range of 1 to 101
>
>I slowly did it this way:
>
>output=zeros(101,101);
>for i=1:27000
>  output( n(i,1),n(i,2) ) = output( n(i,1),n(i,2) ) + 1;
>endfor

You are creating a sparse matrix with summation by hand.
It should work like this:

 output = sparse(n(:,1),n(:2),ones(27000,1),101,101);

-- 
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: Potorti at isti.cnr.it
(entrance 20, 1st floor, room C71)     Web:   http://fly.isti.cnr.it/


More information about the Help-octave mailing list