Re: question about matrix
- To: mathgroup at smc.vnet.net
- Subject: [mg63851] Re: question about matrix
- From: Peter Pein <petsie at dordos.net>
- Date: Thu, 19 Jan 2006 00:02:49 -0500 (EST)
- References: <dqkrvj$pqn$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Tun Myint Aung schrieb: > Dear Mathgroup, > > I have a matrix and it may have rows and columns which are zeros. I > can drop the rows and columns manually but it is troublesome. So my > question is that how to drop the rows and columns that are zeros > automatically. > > Best Regards, > > Tun Myint Aung > Graduate Student > National University of Singapore > E1A #02-18 > Kent Ridge, 119260, Singapore > E-mail g0202015 at nus.edu.sg <mailto:g0202015 at nus.edu.sg> > > > > Hello, it depends on the matrix. If it is an normal array, then DeleteCases[Transpose[DeleteCases[Transpose[matrix], {0 .. }]], {0 .. }]] comes to mind. Let's have a closer look at SparseArrays: First we construct a matrix represented as Table and as SparseArray: SeedRandom[1]; n = 3000; mnormal = Table[(If[#1 > 0.7/n, 0, n*#1*0.7] & )[Random[]], {n}, {n}]; msparse = SparseArray[mnormal, {n, n}]; AbsoluteTiming[Dimensions[ m2 = DeleteCases[Transpose[DeleteCases[Transpose[mnormal], {(0)..}]], {(0)..}]]] --> {0.953125*Second, {1533, 1501}} For SparseArrays, lets change the array rules. Each index is replaced by its position in the union of the indices: AbsoluteTiming[Dimensions[m3 = Module[{ml, mr, mru}, ml = Transpose[Most[First /@ (mr = ArrayRules[msparse])]]; mru = (MapIndexed[#1 -> #2[[1]] & , Union[#1]] & ) /@ ml; mr[[All,1]] = Append[Transpose[MapThread[ReplaceAll, {ml, mru}]], {_, _}]; SparseArray[mr]]]] --> {0.265625*Second, {1533, 1501}} Converting the sparse arry to a normal one and applying method 1 looks easier but is much slower: AbsoluteTiming[Dimensions[ m4 = SparseArray[DeleteCases[Transpose[DeleteCases[ Transpose[Normal[msparse]], {(0)..}]], {(0)..}]]]] --> {1.375*Second, {1533, 1501}} Of course the results are all the same: m2 == m3 == m4 --> True hth, Peter