Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to "search" in a matrix?

  • To: mathgroup at
  • Subject: [mg60901] Re: How to "search" in a matrix?
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at>
  • Date: Mon, 3 Oct 2005 04:06:01 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, U.K.
  • References: <dhnt71$1hu$>
  • Sender: owner-wri-mathgroup at

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.

m = {{"London", "UK", "day1", "temp1"}, {"Paris", "FR", "day1", 
"temp1"}, {"day1", "temp1", "Paris", "TX"},
     {"temp2", "Austin", "TX", "Day2"}};

Position[m, "TX"]

{{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

Position[m, "TX"][[All,1]]

{3, 4}

Now we can get all the lines that are relevant to Texas.


{{"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):

extractLines[mat_, val_] := Module[{m = mat, v = val}, m[[Position[m, 

extractLines[m, "Paris"]

{{"Paris", "FR", "day1", "temp1"}, {"day1", "temp1", "Paris", "TX"}}

Best regards,

  • Prev by Date: "meta-programming" ?
  • Next by Date: Re: simultaneous ... and ___
  • Previous by thread: Re: How to "search" in a matrix?
  • Next by thread: Re: How to "search" in a matrix?