Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid allocating memory for the returned value each time a function is called
    primarykey
    data
    text
    <p>I have a function that returns a large vector and is called multiple times, with some logic going on between calls that makes vectorization not an option. </p> <p>An example of the function is</p> <pre><code>function a=f(X,i) a=zeros(size(X,1),1); a(:)=X(:,i); end </code></pre> <p>and I am doing</p> <pre><code>for i=1:n a=f(X,i); end </code></pre> <p>When profiling this (size(X,1)=5.10^5, n=100 ) times are 0.12s for the zeros line and 0.22s for a(:)=X(:,i) the second line. As expected memory is allocated at each call of f in the 'zeros' line.</p> <p>To get rid of that line and its 0.12s, I thought of allocating the returned value just once, and passing it in as return space each time to an appropriate function g like so:</p> <pre><code>function a=g(X,i,a) a(:)=X(:,i); end </code></pre> <p>and doing</p> <pre><code> a=zeros(m,1); for i=1:n a=g(X,i,a); end </code></pre> <p><strong>What is surprising to me is that profiling inside g still shows memory being allocated in the same amounts at the a(:)=X(:,i); line</strong>, and the time taken is very much like 0.12+0.22s.. </p> <p>1)Is this just <a href="http://blogs.mathworks.com/loren/2006/05/10/memory-management-for-functions-and-variables/" rel="nofollow noreferrer">"lazy copy on write"</a> because I am writing into a? 2)Going forward, what are the options? -a global variable for a (messy..)? -writing a matrix handle class (must I really?) (The <a href="https://stackoverflow.com/questions/1258761/do-i-conserve-memory-in-matlab-by-declaring-variables-global-instead-of-passing-t/1261429#1261429">nested function way</a> means some heavy redesigning to make a nesting function to which X is known (the matrix A with notations from that answer)..)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload