MathGroup Archive 2008

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

Search the Archive

Re: How to use Thread when second argument to function is a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg86442] Re: How to use Thread when second argument to function is a list
  • From: Bill Rowe <readnewsciv at sbcglobal.net>
  • Date: Tue, 11 Mar 2008 03:00:41 -0500 (EST)

On 3/10/08 at 2:04 AM, petsie at dordos.net (Peter Pein) wrote:

>Nasser Abbasi schrieb:

>>I have a function which I want to call repeatedly for all rows of a
>>matrix to find non-zero elements in each row. This function takes
>>as input the row number and the matrix itself and returns a list
>>that contain the non-zero elements in the that row.


>this is a task for Map:

>In[1]:= findNonZeroElements[row_, p_] :=
>Select[p[[row]], #1 != 0 & ]

>mchain[p_] :=
>(findNonZeroElements[#1, p] & ) /@ Length[p]]
>p = {{1, 0, 0, 0, 0},
>{0, 0.2, 0.8, 0, 0}, {0, 0.7, 0.3, 0, 0}, {0.1, 0, 0.1, 0.4, 0.4},
>{0, 0.1, 0.3, 0.2, 0.4}};
>mchain[p] Out[4]= {{1}, {0.2, 0.8}, {0.7, 0.3},
>{0.1, 0.1, 0.4, 0.4}, {0.1, 0.3, 0.2, 0.4}}

>or simply:

>Clear[mchain] mchain[m_]:=MSelect[#, # != 0 &] & /@ m

Another approach would be to use SparseArray.

p = SparseArray[{{1, 0, 0, 0, 0}, {0, 0.2, 0.8, 0, 0}, {0, 0.7, 0.3,
     0, 0}, {0.1, 0, 0.1, 0.4, 0.4}, {0, 0.1, 0.3, 0.2, 0.4}}];
    
then all the non-zero elements can be obtained with

Most[ArrayRules[p]] /. HoldPattern[_ -> a_] :> a

{1,0.2,0.8,0.7,0.3,0.1,0.1,0.4,0.4,0.1,0.3,0.2,0.4}

or for a particular row say row 2

Cases[ArrayRules[p], HoldPattern[{2, _} -> _]] /.
 HoldPattern[_ -> b_] :> b

{0.2,0.8}

--
To reply via email subtract one hundred and four


  • Prev by Date: Re: A question regarding a hyperbolic geometric function
  • Next by Date: Re: FindFit issue
  • Previous by thread: Re: How to use Thread when second argument to function is a list
  • Next by thread: definite integration of 1/a