I am sure the following problem has been solved already, but I am unable to find any solution... Any help appreciated!
So I am building a pretty huge matrix (or tensor, actually) using
mat=SparseArray[ParallelTable[UnitStep[f[a,b,c,d]],{a,1,D},{b,1,D},{c,1,D},{d,1,D}]]]
In my specific case I have D=180
and f
is a simple function (basically addition or subtraction of certain elements stored in a short list), such that the majority of the values UnitStep[f[...]]
are zeros and the resulting matrix is indeed sparse.
Now, constructing this array takes quite some time, but more problematically, it uses around 12 GB of memory during the computation. I want to use less memory, but I do not know how. However, I think it should be possible because it is a very sparse array containing only zeros and a few ones. In particular, using
Export["mat.mx",max]
the final file on my computer is only 12 MB (instead of GB). Is there a better way?
f
, it's hard to give advice. Anyway, if I have to guess, building theSparseArray
from rules rather than converting a normal tensor to aSparseArray
should help. (See the examples in document ofSparseArray
for more info. ) $\endgroup$f
may be more efficient than parallelizing. But as @xzczd says, nothing can be said without details onf
. $\endgroup$UnitStep
, and given the information that the resulting sparse matrix is much smaller than the intermediate result, it is possible to conclude thatUnitStep[f[...]]
produces mostly zeros, and that the author wants to avoid consuming too much memory for the intermediate result. After that assumption, the question becomes well-defined. $\endgroup$mat = SparseArray[Reap[Do[val = UnitStep[f[a, b, c, d]]; If[val != 0, Sow[{a, b, c, d} -> val]], {a, 1, top}, {b, 1, top}, {c, 1, top}, {d, 1, top}]][[2, 1]]];
$\endgroup$