Test case:
data = RandomReal[1, {1000, 1000}];
pos = RandomInteger[{1, 1000}, {5*10^5, 2}];
r1 = ReplacePart[data, pos -> 0]; // AbsoluteTiming
(data[[##]] = 0) & @@@ pos; // AbsoluteTiming
data == r1
(*
{3.433196, Null}
{1.892108, Null}
True
*)
The similar matlab code only takes about 0.16 second:
tic;
A=rand(1000,1000);
pos= randperm(5e5);
A(pos)=0;
toc;
(*Elapsed time is 0.166717 seconds.*)
I am looking for a more efficient way.
Answer
I think it's worth noting that the two random position codes you list aren't the same. If you want to do something like randperm in Mathematica you should use RandomSample
. In addition to this, what you are trying to do is effectively to simultaneously address a large number of positions in the matrix. In Mathematica I do not believe you can do this for matrixes and other things with larger dimensions, however for a single list you can do this with speeds similar to MATLAB:
SeedRandom[322112432]
data = Flatten[RandomReal[1., {1000, 1000}], 1];
pos = RandomSample[Range[1, 5*10^5]];
Module[{temp = Flatten[data, 1]},
temp[[pos]] = 0.;
data = Partition[temp, 1000]
]; // AbsoluteTiming // First
(* 0.014001 *)
Where MATLAB returns Elapsed time is 0.058448 seconds.
on my system. I believe the root of the difference here is that MATLAB treats your matrix like it was just a long list, and only uses the dimensions to translate between indexing using two coordinates and the singular index, while Mathematica has a more general structure, where you can't just assume that each row is the same length for the purpose of simultaneous indexing, which might be why you can't just do something like for instance data[[index[1,2],index[2,3]]]=0
for a matrix, even though you can do data[[{1,2}]]=0
for a list.
Comments
Post a Comment