Why does setting individual elements in a large matrix take so long?
Info
This question is closed. Reopen it to edit or answer.
Show older comments
I have a sub-function that was taking a really long time, so I profiled it (Matlab 2012b). Here is the relevant excerpt:
function [dslope, endb] = fixStream(s, b, dslope, endb)
for i=1:length(s.u)
ui = s.u(i);
vi = s.v(i);
ds = dslope(vi,ui);
if ds < b
b = ds;
if b < 0
break;
end
end
assert(numel(ui)==1 && numel(vi)==1);
dslope(vi,ui) = 0; %ds - b;
end
endb(s.id) = b;
When I fire up the profiler, it tells me that the dslope(vi,ui) = 0 line is what is causing the problem -- only 291 calls takes 18.9 seconds!! dslope is a big (10800x10800) double matrix and ui and vi are just integer indexes into that matrix. When I try to reproduce the problem in stand alone code, I can't do it -- this works fine (elapsed time of basically nothing for the for loop):
N = 10800;
z = rand(N);
uv = floor(rand(1000,2)*N)+1;
tic;
for i=1:size(uv,1)
z(uv(i,1),uv(i,2)) = 0;
end
toc
What could possibly be going on here?
Answers (1)
Ben
on 18 May 2013
2 Comments
Philip Borghesani
on 20 May 2013
The precalculation of the value ds0 is allowing the inplace optimization to take place without it each call to fixStream must copy dslope when it is modified.
Ben
on 21 May 2013
This question is closed.
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!