MathGroup Archive 2009

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

Search the Archive

Re: Given a matrix, find position of first non-zero element

  • To: mathgroup at smc.vnet.net
  • Subject: [mg99515] Re: [mg99492] Given a matrix, find position of first non-zero element
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Thu, 7 May 2009 06:33:39 -0400 (EDT)
  • References: <200905060929.FAA02194@smc.vnet.net>

Hi,

Range@Length@A /. Map[#[[1]] -> # &, Position[A, _?(# != 0 &)]]

or

Split[Position[A, _?(# != 0 &)], #1[[1]] == #2[[1]] &][[All, 1]]

or

Transpose[{Range[Length[A]], LengthWhile[#, # == 0 &] + 1 & /@ A}]

or

Map[Scan[If[#[[1]] != 0, Return@#[[2]]] &, #] &, MapIndexed[List, A, {2}]]

or (purely patterns, but quite a hack)

Module[{n = 1},  A1 /. {0 -> 1, _Integer -> 0} /.
{{x___, 0, ___} :> {n++, x + 1}, {___Integer} :> (n++ /. _ :> Sequence[])}]


or...


Regards,
Leonid


On Wed, May 6, 2009 at 2:29 AM, Nasser Abbasi <nma at 12000.org> wrote:

> This is a little problem I saw in another forum, and I am trying to also
> solve it in Mathematica.
>
> Given a Matrix, I need to find the position of the first occurance of a
> value which is not zero in each row.
>
> The position found will be the position in the orginal matrix ofcourse.
>
> So, given this matrix,
>
> A = {
> {0, 0, 5},
> {50, 0, 100},
> {0, 75, 100},
> {75, 100, 0},
> {0, 75, 100},
> {0, 75, 100}
> };
>
> The result should be
>
> {{1, 3}, {2, 1}, {3, 2}, {4, 1}, {5, 2}, {6, 2}}
>
> This is how I solved this problem and after a bit of  struggle. I wanted to
> see if I could avoid using a Table, and solve it just using Patterns and
> Position and Select, but could not so far.
>
>
> Table[Flatten[{i, Flatten[Position[A[[i,All]], _?(#1 != 0 & ), 1, 1]]}],
> {i,
> 1, 6}]
>
> Out[174]= {{1, 3}, {2, 1}, {3, 2}, {4, 1}, {5, 2}, {6, 2}}
>
> I am not happy with the above solution. I am sure there is a better one
> (the
> above also do not work well when one row has all zeros).
>
> Do you see a better and more elegant way to do this?
>
> thanks,
> --Nasser
>
>
>
>


  • Prev by Date: Re: RegionPlot3d under sampling plot points?
  • Next by Date: Re: Some function like Position[] but uses criteria, not pattern?
  • Previous by thread: Re: Given a matrix, find position of first non-zero element in each row
  • Next by thread: Re: Given a matrix, find position of first non-zero element