From: joseph Frank on
Hi ,

I have a list of years example;

A=[1990;1992;1996;1997;1998];
and I have B=1993;

The year of B is not in A but I would like to find the closest previous year to this number (i.e 1992 second observation in A). Is their a function to do this ?
Thanks
From: John D'Errico on
"joseph Frank" <josephfrank1969(a)hotmail.com> wrote in message <hrh52c$bf6$1(a)fred.mathworks.com>...
> Hi ,
>
> I have a list of years example;
>
> A=[1990;1992;1996;1997;1998];
> and I have B=1993;
>
> The year of B is not in A but I would like to find the closest previous year to this number (i.e 1992 second observation in A). Is their a function to do this ?
> Thanks

Look at the second return argument from histc.

John
From: dpb on
joseph Frank wrote:
> Hi ,
>
> I have a list of years example;
>
> A=[1990;1992;1996;1997;1998];
> and I have B=1993;
>
> The year of B is not in A but I would like to find the closest previous
> year to this number (i.e 1992 second observation in A). Is their a
> function to do this ?
> Thanks

I didn't see the trick to John's histc() answer--I'm sure there's
something obvious I'm overlooking.

interpt1() has "nearest" option but won't guarantee nearest is lower
than interpolant...

My contribution...

>> tmp=A(A<B); lowinterpolant = tmp(end)
lowinterpolant =
1992
>>

--
From: dpb on
dpb wrote:
....

> >> tmp=A(A<B); lowinterpolant = tmp(end)
> lowinterpolant =
> 1992
> >>

Better...eliminates temporary

max(A(A<B))

--
From: John D'Errico on
dpb <none(a)non.net> wrote in message <hrh7nr$mj5$1(a)news.eternal-september.org>...
> joseph Frank wrote:
> > Hi ,
> >
> > I have a list of years example;
> >
> > A=[1990;1992;1996;1997;1998];
> > and I have B=1993;
> >
> > The year of B is not in A but I would like to find the closest previous
> > year to this number (i.e 1992 second observation in A). Is their a
> > function to do this ?
> > Thanks
>
> I didn't see the trick to John's histc() answer--I'm sure there's
> something obvious I'm overlooking.

Look at the help for histc.

A = [1990;1992;1996;1997;1998];

[junk,index] = histc(1993,A);
A(index)
ans =
1992

The virtue of histc here is it is VECTORIZED and
comparatively FAST as blazes. If you have a million
points, still fast.

The test as you have done it is not so fast. In fact,
the test as you have done it is not even vectorized,
so you would need to loop over multiple points.

John
 |  Next  |  Last
Pages: 1 2
Prev: regionprops
Next: regionprops