slow re-assignment of values to an array in a structure

2 views (last 30 days)
Here is my problem: Why does line 6 below take two orders of magnitude more time to compute than other instances of the same command?
1.>> x = ones(100,100,250);
2.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000433 seconds.
3.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000420 seconds.
4.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000417 seconds.
5.>> s.x = x;
6.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.013906 seconds.
7.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000435 seconds.
8.>> tic; x(:,:,23) = rand(100,100) ; toc
Elapsed time is 0.000537 seconds.
*******
In my application I send a large structure of arrays into a subroutine and I observe it running super slowly and I think this is the issue.
Any explanation?

Accepted Answer

Matt Fig
Matt Fig on 6 Apr 2011
Sorry, at first I didn't read the whole question.
My guess is that line 5 doesn't actually copy the data in x. When you change x the copy happens. Before the copy happens, s.x only "points" to the values in x. This is a MATLAB "efficiency" known as copy-on-write.
See Loren's response number 6.
.
.
EDIT
Here is how really to see this:
format debug
x = [2,2] % Look at pr, this is the pointer in memory
s.x = x; % Make assignment...
s.x % Same pr here as above for x.
% Now change x and look at the pointers...
x = 5; % Make change.
x
s.x % Different pr now
  3 Comments
Matt Fig
Matt Fig on 7 Apr 2011
Nice approach, Jiro! Here is even more evidence of what happens, as if we needed any at this point:
>> clear all, pack
>> tic,x = rand(10000);toc
Elapsed time is 5.906108 seconds.
>> tic,y = x;toc
Elapsed time is 0.000041 seconds.
>> tic,x(1) = 3;toc
??? Out of memory. Type HELP MEMORY for your options.
Now you just gotta ask, how could this have run MATLAB out of memory?

Sign in to comment.

More Answers (1)

Jonathan
Jonathan on 10 Apr 2011
Thanks guys! Much appreciated. So it is the accursed "copy on write" thing. If only I could pass array pointers to Matlab subroutines.....

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!