|
"Nasser M. Abbasi" <nma@12000.org> wrote in message <jrmss6$de5$1@speranza.aioe.org>...
> On 6/18/2012 4:08 AM, Nasser M. Abbasi wrote:
> > On 6/18/2012 2:48 AM, Jainam wrote:
> >> Dear MATLAB users,
> >>
> >> I have a very tricky situation (at least it seems tricky to me).
> >> I have a binary array, lets say,
> >> a = [ 0 1 1 0 0 1 1 1 0 0 1 0 1 1 1 1 0 1 1 1 ]; (length = 20)
> >> Now from this array I want to find the maximum number of 1s TOGETHER,
> >> not the number of 1s in the whole array (here maximum number of 1s
> >> is 13 but max. number of 1s TOGETHER is 4).
> >> So, in this array 'a', the maximum number of 1s TOGETHER is
> >> 4 (i.e. from array elements 13 to 16). Position of 1s does not matter.
> >>
> >> Thanks in advance!!
> >> Jainam
> >>
> >
>
>
> > What is wrong with a simple loop?
> >
> > -----------------------
> > a = [ 0 1 1 0 0 1 1 1 0 0 1 0 1 1 1 1 0 1 1 1 ];
> > N = length(a);
> > b = zeros(1,N);
> > b(1) = a(1);
> >
> > for i = 2:N
> > b(i) = a(i)*(a(i)+b(i-1));
> > end
> >
> > [I,J]=max(b);
> > -----------------------
> >
> > fprintf('starts at %d\n',J-I+1);
> > fprintf('ends at %d\n',J);
> >
> > starts at 13
> > ends at 16
> >
> > --Nasser
> >
>
> If you just want the LENGTH of the longest 1's (and
> not care where it starts or ends), you can
> use this nice trick that I picked up from a post by Bruno
> to this newsgroup
>
> ------------------------------
> x = find(diff([0 a]) == 1);
> y = find(diff([a 0]) == -1);
> max(y-x+1)
> --------------------------
> ans =
>
> 4
>
> notice you need to do the [0 a] and [a 0] to get the
> lengths right and have to check for 1 and -1 also.
>
> see reference:
>
> http://www.mathworks.com/matlabcentral/newsreader/view_thread/312417
>
> --Nasser
ya, this approach is very smart too! thanks again nasser!!
|