2
$\begingroup$

I have to replace all the elements smaller than 0 in a large matrix to 0.But i found the speed is really slow when the matrix is big. Here is my code. a=RandomReal[NormalDistribution[],{1000,1000}]; AbsoluteTiming[a//. {{aa___, i_, bb___} /; i < 0 -> {aa, 0., bb}};] Do you have any suggestions?

$\endgroup$

1 Answer 1

10
$\begingroup$

Some (much much faster) alternatives:

a = RandomReal[NormalDistribution[], {1000, 1000}];
Clip[a, {0, Infinity}]
a /. q_ /; q < 0 -> 0.
Ramp[a]
% == %% == %%%
(* True *)

(the last one is untested, because I'm using v.10)

$\endgroup$
5
  • $\begingroup$ Thanks i have though an idea :panduan[i] := Piecewise[{i, i > 0}]; Attributes[panduan] = Listable; $\endgroup$
    – XinBae
    Jul 31, 2018 at 2:08
  • $\begingroup$ @xinpei Indeed, your idea is equivalent to the Ramp approach. Nice! (although I believe you are missing a pair of brackets: Piecewise[{{i, i > 0}}]) $\endgroup$ Jul 31, 2018 at 2:09
  • $\begingroup$ ...your code is better and i have wirte wrong code $\endgroup$
    – XinBae
    Jul 31, 2018 at 2:16
  • $\begingroup$ @xinpei No problem, you were on the right track :-) I'm glad I could help, cheers! $\endgroup$ Jul 31, 2018 at 2:24
  • $\begingroup$ (+1) for Ramp. $\endgroup$ Jul 31, 2018 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.