help-octave
[Top][All Lists]
Advanced

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

Re: How do I replace this for-loop?


From: Robert Macy
Subject: Re: How do I replace this for-loop?
Date: Sat, 05 Jul 2008 20:43:27 -0700

It worked,...quite fast, too

Thank you, you've introduced me to new functions here.  

Robert

On Sat, 05 Jul 2008 19:33:48 -0700
 Ben Abbott <address@hidden> wrote:
>  
> On Saturday, July 05, 2008, at 03:20PM, "Martin Weiser"
> <address@hidden> wrote:
> >On Sat, 5 Jul 2008, Martin Weiser wrote:
> >
> >> On Fri, 4 Jul 2008, Robert Macy wrote:
> >>
> >>> What's the best way to replace this for-loop?
> >>>
> >>> 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
> >>>
> >>> as you all know this is fairly slow.
> >>> What's a simple way to replace this for-loop?
> >>>
> >>> Robert
> >>>
> >> Hi,
> >> what about something like:
> >> ni=zeros(27000,1);
> >> ni=sub2ind(size(n),n(:,1),n(:,2));
> >> ni=sort(ni);
> >> [breaks,garbage,indeces]=find(ni-shift(ni,1);
> >> times=breaks-shift(breaks,1);
> >> output=zeros(101,101);
> >> output(indeces)=times;
> >>
> >> (I would guess that people here will come with
> something much more
> >> straightforward and elegant, maybe with an one-liner.)
> >> I have not tested that, but HTH
> >> Martin W.
> >
> >Hello,
> >I am sorry, I have realized now that I was almost
> completely wrong.
> >Sorry again,
> >Martin W. 
> 
> Martin, 
> 
> Actually, you weren't so far off. Your attempt gave me
> the inspiration needed to produce the result below. For
> testing purposes, I created a random version for "n".
> 
> N   = 27000;
> M   = 101;
> output = zeros (M, M);
> n   = round ((M-1) * rand([N, 2])) + 1;
> ni  = sub2ind (size (output), n(:,1), n(:,2));
> ni  = sort (ni);
> ni  = [ni; max(ni)+1];
> fdni = find (diff (ni));
> num = diff ([0;fdni]);
> mi  = ni(fdni);
> output(mi) = num;
> 
> Robert, As I am a 3.0.1/3.0.0+ user, I have no idea if
> this will work for Octave 2.1.50a. 
> 
> Ben
> 



reply via email to

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