Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As noted by <a href="http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/">Loren on his blog</a>, MATLAB does support <strong>in-line</strong> operations on matrices, which essentially covers passing arrays by reference, modifying them in a function, and returning the result. You seem to know that, but you erroneously state that <em>because the script must contain identical variable names as the calling script</em>. Here is code example that shows this is wrong. When testing, please copy it verbatim and save as a function:</p> <pre><code>function inplace_test y = zeros(1,1e8); x = zeros(1,1e8); tic; x = compute(x); toc tic; y = compute(y); toc tic; x = computeIP(x); toc tic; y = computeIP(y); toc tic; x = x+1; toc end function x=computeIP(x) x = x+1; end function y=compute(x) y = x+1; end </code></pre> <p>Time results on my computer:</p> <pre><code>Elapsed time is 0.243335 seconds. Elapsed time is 0.251495 seconds. Elapsed time is 0.090949 seconds. Elapsed time is 0.088894 seconds. Elapsed time is 0.090638 seconds. </code></pre> <p>As you see, the two last calls that use an <strong>in-place</strong> function are equally fast for both input arrays <code>x</code> and <code>y</code>. Also, they are equally fast as running <code>x = x+1</code> without a function. The only important thing is that <strong>inside the function</strong> input and output parameters are the same. And there is one more thing...</p> <p>If I should guess what is wrong with your code, I'd say you made <strong>nested</strong> functions that you expect to be in-place. And they are not. So the below code will not work:</p> <pre><code>function inplace_test y = zeros(1,1e8); x = zeros(1,1e8); tic; x = compute(x); toc tic; y = compute(y); toc tic; x = computeIP(x); toc tic; y = computeIP(y); toc tic; x = x+1; toc function x=computeIP(x) x = x+1; end function y=compute(x) y = x+1; end end Elapsed time is 0.247798 seconds. Elapsed time is 0.257521 seconds. Elapsed time is 0.229774 seconds. Elapsed time is 0.237215 seconds. Elapsed time is 0.090446 seconds. </code></pre> <p>The bottom line - be careful with those nested functions..</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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