# 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[]]}], "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. – DumpsterDoofus Nov 22 '14 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[]]}]]]


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. – Amandeep Nov 23 '14 at 5:55
• My answer revised to more closely match your question revised. – Bill Nov 23 '14 at 20:43
• matrixx = Table[Subscript[m, i, j], {i, 9}, {j, 9}] matrixx[[1 ;; 1, 1 ;; 9]] = 0 i have used above syntax written by you to check it on simple problem. But I think it is not working. You should look at this example too. it should print all the remaining rows of matrixx. – Amandeep Nov 23 '14 at 21:57
• So use === instead of ==. matrixx = Table[Subscript[m, i, j], {i, 9}, {j, 9}]; matrixx[[1 ;; 1, 1 ;; 9]] = 0; StringJoin[Flatten[Table[If[matrixx[[i, j]] === 0, "", "matrix(" <> ToString[i] <> "," <> ToString[j] <> ") = " <> ToString[matrixx[[i, j]]] <> "\n"], {i, Length[matrixx]}, {j, Length[matrixx[]]}]]] but I urge you to not use subscripts, no matter how desperately you believe you must use subscripts. – Bill Nov 24 '14 at 17:35
• Thanks. Anyways subscript I mentioned was just for example. In my work, I am not using it. I know the problem I will face with that. Thanks anyways. – Amandeep Nov 25 '14 at 18:43