# Opposite function to Normal

Is there any function opposite to Normal? For example, let as say that I have an SparseMatrix A, then, let as say that for convenience for a certain operation like Packing, I convert it into an Array by doing

A=Normal[A];


and afterwards, I want A to became an SparseArray again.

Is there anyway to do this without the need to define the matrix A again?

Thanks

• In case there is no such function, a way to solve this problem is to define A_backup =A, then, A=Normal[A] and afterwards A=A_backup. – Mencia Dec 15 '13 at 17:41
• SparseArray[A] – ssch Dec 15 '13 at 17:42
• @ssch thankyou! – Mencia Dec 15 '13 at 17:44

## 1 Answer

If the background value is 0 just run SparseArray on it:

sp = SparseArray[Band[{1, 1}] -> 1, {100, 100}];
ByteCount[sp]
(* 2152 *)

nrm = Normal[sp];
ByteCount[nrm]
(* 40168 *)

sp2 = SparseArray[nrm];
ByteCount[sp2]
(* 2152 *)


If it has another background value do SparseArray[nrm, Automatic, background], if you don't know the background value use the commonest element, which is First@Commonest[Flatten@nrm]

• what is the background value? – Mencia Dec 15 '13 at 17:49
• @Mencia the default value that is used where nothing else is specified in the SparseArray e.g. SparseArray[Band[{1,1}]->9, {5,5}, Infinity]//Normal//MatrixForm – ssch Dec 15 '13 at 17:54
• but the best is to specify them as zero right? since zero terms will not take up memory in the SparseArray – Mencia Dec 15 '13 at 17:59
• @Mencia Doesn't matter what it is, SparseArray only stores information representing position and value for places where the value is not equal to the background value, so for memory use it doesn't matter what the background happens to be. However 0 is very common and is usually what you want (this is why Mathematica assumes you want 0 unless you specify otherwise) – ssch Dec 15 '13 at 18:04
• @Mencia Here's link to some documentation: tutorial/SparseArrays-ManipulatingLists. It implies what ssch says here, but it's not as clear as this answer. :) – Michael E2 Dec 15 '13 at 18:09