Path: news.mathworks.com!newsfeed-00.mathworks.com!NNTP.WPI.EDU!elk.ncren.net!newsflash.concordia.ca!canopus.cc.umanitoba.ca!not-for-mail
From: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to find vector value via matrix value?
Date: Mon, 21 Jul 2008 19:23:40 +0000 (UTC)
Organization: National Research Council Canada - Conseil national de rechereches Canada
Lines: 40
Message-ID: <g62nns$s4g$1@canopus.cc.umanitoba.ca>
References: <g62lhb$4sn$1@fred.mathworks.com>
NNTP-Posting-Host: origin.ibd.nrc.ca
X-Trace: canopus.cc.umanitoba.ca 1216668220 28816 192.70.172.160 (21 Jul 2008 19:23:40 GMT)
X-Complaints-To: abuse@cc.umanitoba.ca
NNTP-Posting-Date: Mon, 21 Jul 2008 19:23:40 +0000 (UTC)
Originator: roberson@ibd.nrc-cnrc.gc.ca (Walter Roberson)
Xref: news.mathworks.com comp.soft-sys.matlab:480746



In article <g62lhb$4sn$1@fred.mathworks.com>,
Ning  <ning.robin@gmail.com> wrote:
>Say I have a 2x3 matrix m and vector v.
>m = [1.1,1.7,2.1;...
>     3.6,3.3,4.2];
>v=[0 1 2 3 4]';
>If I want to find the nearest value of m in v,in this case, 
>let the nearest value matrix is nm, then 
>nm=[1 2 2;...
>   4 3 4];
>How to find the matrix nm without loop?

>> interp1(v,v,m,'nearest')

ans =

     1     2     2
     4     3   NaN

You can improve this to,

>> interp1(v,v,m,'nearest',max(v))

ans =

     1     2     2
     4     3     4


but if you had a value less than the smallest in v then that value
would be replaced by max(v) rather than min(v). The easiest way to deal
with this is likely:

m1 = m;
m1(m1 < min(v(:))) = min(v);
m1(m1 > max(v(:))) = max(v);
interp1(v,v,m1,'nearest')
-- 
  "I like to build things, I like to do things. I am having
  a lot of fun."                              -- Walter Chrysler