Converting matlab sparse matrix to single precision

Solution 1:

You can find indices of non zero elements and use that to change the matrix;

idx = find(A);
Anz = A(idx);
idx = idx(Anz < 2^-126);
A(idx) = 0;

Or more compact:

idx = find(A);
A(idx(A(idx) < 2^-126)) = 0;

However if you want to convert from double to single you can use single function:

idx = find(A); 
A(idx) = double(single(full(A(idx))));

or

A(find(A)) = double(single(nonzeros(A)));

To convert Inf to realmax you can write:

A(find(A)) = double(max(-realmax('single'),min(realmax('single'),single(nonzeros(A)))));

If you only want to convert Inf to realmax you can do:

Anz = nonzeros(A);
AInf = isinf(A);
Anz(AInf) = double(realmax('single')) * sign(Anz(AInf));
A(find(A)) = Anz;