Why can't I reshape to any dimensions?
ArrayReshape[SparseArray`SparseArrayFlatten[m], {1, 8}]
(* or ArrayReshape[Flatten[m], {1, 8}] *)
SparseArray[<2>,{1,8}]
Normal @ %
{{1, 0, 0, 0, 0, 0, 0, 1}}
For the special case where the desired shape is a list with Length
equal to Times@@Dimensions[m]
, you can also use SparseArray`SparseArrayFlatten
:
SparseArray`SparseArrayFlatten[m]
SparseArray[<2>,{8}]
Normal @ %
{1, 0, 0, 0, 0, 0, 0, 1}
It seems one have to make SparseArray
to Normal
first to reshape it.
m=SparseArray[{i_,i_,i_}->1,{2,2,2}];
ArrayReshape[m,{1,8}]//Normal
But now
ArrayReshape[Normal@m,{1,8}]
Not sure if this is by design or not.
Comparing the timings for the approaches proposed by kglr
and Nasser
(modified):
$HistoryLength = 0;
m = SparseArray[{i_, i_, i_} -> 1., {16, 16, 16}];
(kglr = ArrayReshape[SparseArray`SparseArrayFlatten[m], #] & /@ {{1,
16^3}, {16^3, 1}, {128, 32}, {32, 128}}) // RepeatedTiming
(nasser = SparseArray@ArrayReshape[Normal@m, #] & /@ {{1, 16^3}, {16^3,
1}, {128, 32}, {32, 128}}) // RepeatedTiming
Verifying their equivalence
kglr === nasser
True