# How to print non zero elements of the matrix containing zero elements and non-zero elements both?

A matrix with both non-zero and zero elements is given. I want to print only the non-zero elements of the matrix. What is syntax that have to be used for this?

matr2 = Table[FortranForm[matrixx[[i, j]]], {i, 12}, {j, 12}]; matr3 = ExportString[ Flatten@Table[ "matrix(" <> ToString[i] <> "," <> ToString[j] <> ") = " <> ToString[matr2[[i, j]]], {i, Length[matr2]}, {j, Length[matr2[[1]]]}], "Table"] CopyToClipboard[matr3]

This commnand prints the data of matrix matr2 as matrix(1,1)=a11 element of matr2. So my question is related to this that is if i want to print only the non-zero elements of matr2? what syntax should i have to added in this?

• You can use DeleteCases[#, 0] & /@ mat. Commented Nov 22, 2014 at 16:32

Perhaps this example

matrix = RandomInteger[{0, 2}, {3, 3}]; matrix // MatrixForm

which displays thiis

0 0 2
1 0 2
0 0 1


Then this

matrix /. v_ /; v == 0 -> "" // MatrixForm


which displays this

    2
1   2
1


EDIT/Append

I saw you revised your question after I posted the above. Perhaps you can adapt this:

StringJoin[Flatten[Table[
If[matrixx[[i, j]] == 0, "", "matrix("<>ToString[i]<>","<>ToString[j]<>") = " <>
ToString[matrixx[[i, j]]]<>"\n"], {i, Length[matrixx]}, {j, Length[matrixx[[1]]]}]]]


Once you have turned something into a *Form, whether MatrixForm or FortranForm or *Form, that might make it pretty to look at but you often can't do any further calculations with that until you strip off the *Form and most new users are not aware of this or understand how to do this.

• please take a look at my edited question. Commented Nov 23, 2014 at 5:55