1

I am implementing the adaptive Simpsons method in Matlab recursively. I wish to store all of the points where function evaluations take place to generate a histogram after integrating. I currently have:

function [S, points] = adsimp(f, a, b, fv, tol, level, points)
...
d = (a+b)*0.25;
e = (a+b)*0.75;
points = [points, d, e];
...

Thus, for every function call, I am increasing the length of points by two. My understanding of Matlab's function input/output scheme is poor. I'd like to know:

1) When the input and output share a variable name, does this use a single variable, or is a local copy made and then returned?

2) If it is a copy, is there a way to pass points by reference and preallocate sufficient memory?

dinkelk
  • 2,676
  • 3
  • 26
  • 46
nicktruesdale
  • 815
  • 5
  • 12

1 Answers1

1

To answer your first question, see here. Most MATLAB variables are passed by value (matrices, etc.) unless it is a handle object (function handle, axis handle etc.) A local copy of an input variable is made only if that variable is altered in the function. ie.

function y = doTheFunc1(x)
    x(2) = 17;
    y = x;

a copy must be made. As opposed to:

function y = doTheFunc2(x)
    y = x(1);

where no copy need be made inside the function. In other words, MATLAB is a "copy on write" language. I am almost certain this is true regardless what your output variable output name is (ie. this holds even if your output and input are both named x).

To answer your second question, look at the first answer here. Consider using a nested function or a handle object.

Community
  • 1
  • 1
dinkelk
  • 2,676
  • 3
  • 26
  • 46