Re: How to "search" in a matrix?
- To: mathgroup at smc.vnet.net
- Subject: [mg60901] Re: How to "search" in a matrix?
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Mon, 3 Oct 2005 04:06:01 -0400 (EDT)
- Organization: The Open University, Milton Keynes, U.K.
- References: <dhnt71$1hu$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Renan wrote:
> I have this matrix:
>
> matr = {{a, b, 1}, {c, d, 2}, {e, f, 3}}
>
> I'm trying to do a "search" in a matrix. The "real" matrix will contain strings.
> How to "search" for a given value in a matrix and return all lines that have it?
>
> 'Select' seems to handle only lists - and this would require a
> Flatten, probably making my code too complicated and maybe slow (the
> real matrix will contain something like 100 elements - weather data).
>
> Thanks.
>
Hi Renan,
One way of doing what you want is using the *Position* built-in
function. Say, we have a 4x4 matrix with some string data and we are
looking for the lines that contain information about Texas.
In[1]:=
m = {{"London", "UK", "day1", "temp1"}, {"Paris", "FR", "day1",
"temp1"}, {"day1", "temp1", "Paris", "TX"},
{"temp2", "Austin", "TX", "Day2"}};
In[2]:=
Position[m, "TX"]
Out[2]=
{{3, 4}, {4, 3}}
The command returns the exact location -- row and column -- of the
string "TX" within the matrix m. Since we want the whole lines, we get
rid of the column as in
In[3]:=
Position[m, "TX"][[All,1]]
Out[3]=
{3, 4}
Now we can get all the lines that are relevant to Texas.
In[4]:=
m[[%]]
Out[4]=
{{"day1", "temp1", "Paris", "TX"}, {"temp2", "Austin", "TX", "Day2"}}
Finally, we can wrap these different steps in one convenient function,
say, _extractLines_ that take two arguments and return a matrix (list of
lists in Mathematica):
In[5]:=
extractLines[mat_, val_] := Module[{m = mat, v = val}, m[[Position[m,
v][[All,1]]]]]
In[6]:=
extractLines[m, "Paris"]
Out[6]=
{{"Paris", "FR", "day1", "temp1"}, {"day1", "temp1", "Paris", "TX"}}
Best regards,
/J.M.