I'm having a hard time finding a solution that's faster than the original loop...
n_values = 10000;
nc = 100;
pre_matrix = rand(n_values,nc);
sz = size(pre_matrix);
J = cell(1,n_values);
for ii = 1:n_values
n0 = randi(nc,1);
J{ii} = randi(nc,1,n0);
end
tic
for i=1:n_values
pre_matrix(i,J{i})=0;
end
toc
tic
I = cell(size(J));
for ii = 1:n_values
I{ii} = ii.*ones(size(J{ii}));
end
idx = sub2ind(sz, cat(2, I{:}), cat(2, J{:}));
pre_matrix(idx) = 0;
toc
tic
I = cellfun(@(a,b) ones(size(a)).*b, J, num2cell(1:n_values), 'uni', 0);
idx = sub2ind(sz, cat(2, I{:}), cat(2, J{:}));
pre_matrix(idx) = 0;
toc
Results:
Elapsed time is 0.017597 seconds. <- loop
Elapsed time is 0.047797 seconds. <- indexing with loop
Elapsed time is 0.119106 seconds. <- indexing with cellfun
My guess here is perhaps the culprit is that missing semicolon in the loop? If you're printing out the huge matrix every iteration, that's definitely going to take some time! But the loop itself is pretty fast.
0 Comments
Sign in to comment.