Hacker News new | past | comments | ask | show | jobs | submit login

The final MATLAB example of "Inplace modification" is not correct.

  function f(out, x)
       out = x.^2
  x = rand(10)
  y = zeros(length(x), 1)
  f(y, x)

What happens here when you call f(y, x) is:

1. The arrays x and y are passed to f (no memory copying done yet, since MATLAB uses copy on write)

2. When we have `out = x.^2`, this will allocate a new array in memory and store in it the result of `x.^2`, and will call this `out`. The original `out` which was passed into the function can now be garbage collected (although it won't be, because it's still in the parent scope as 'y')

3. When the function exits, the new `out` goes out of scope and can be garbage collected.

So all this example does is allocate a new array, assign x.^2 to it, and then throw that result away again. There's no in-place modification.

You can't really pass a matrix by reference in MATLAB like you can in Python, however in some cases you can write your function in a specific way which will ensure in place operations are done and prevent a huge matrix copy. For example (pauses are just there so that you can watch task manager memory usage):

  function x = inPlace()
      x = rand(100000000, 1);
      x = doSomething(x);

  function y = doSomething(y)
      y = y.^2;
Conditions required are:

* Input and output variables must have same name in caller

* Input and output variables must have same name in callee

* Callee must be inside a function, not a script

Look here for a more detailed description: https://blogs.mathworks.com/loren/2007/03/22/in-place-operat...

Registration is open for Startup School 2019. Classes start July 22nd.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact