Hi,
I would suggest to introduce some cutoff epsilon, so that if the total of
any row
or column is less than epsilon, the row(column) is considered zero. This
will
speed up things considerably.
Consider a test "random" matrix:
In[1] =
testMatrix =
{{0.0000273478, 0.00003388, 17., 12.0001, 7.00002,
12.0001},
{0.0000192929, 0.0000107438, 0.0000910806, 0.0000370966,
0.000055372, 0.0000476642},
{0.0000649353, 0.0000388735, 17., 18.,
18., 18.},
{0.0000503573, 0.0000859998, 0.0000592802, 0.000086099,
0.0000915784, 8.01093*10^-6}};
(I made the small (zero) elements relatively large to avoid messy input). If
you set up
epsilon = 0.001, then rows 2,4 are zeros, as well as columns 1,2.
Here is then the code for the function that does what you want:
In[2] =
removeZeros[matr_, epsilon_] :=
Nest[***@Select[#, Total[Abs[#]] > epsilon &] &, matr, 2];
In[3] = removeZeros[testMatrix, 0.001]
Out[3] = {{17., 12.0001, 7.00002, 12.0001}, {17., 18., 18., 18.}}
If you need to delete only rows, use Select[#, Total[Abs[#]] > epsilon &]
&@matr
in the above definition, while if you need to delete only columns, use
Transpose[Select[#, Total[Abs[#]] > epsilon &] &@Transpose[matr]]
By making epsilon as small as you wish, you should be able to get what you
need.
At the same time, this solution will have a near linear complexity in the
maximal
matrix dimension (for the matrices not enormously large), while if you would
test element by element, you will end up with roughly quadratic complexity.
Regards,
Leonid
Post by KFUPMDear all
I have large matrices having entire rows and/or columns of zeros and I
want to delete those zero rows and columns. My question, what is the
best (most compact) command to use in Mathematica. Please note that
the value of zero is the real zero i.e 0.0000 not just 0.
Regards,