4

What I am wondering about is how does matlab pass a structure to a function or method of a matlab class and how does it return it. Lets say I have the following code

foo.var1 = 3;
foo.var2 = [1 2 3 4];

function return_foo = my_fun(structure)
    structure.var1 = structure.var1 + 7;
    structure.var2 = 2*structure.var2;
    return_foo = structure;
end

and then call my_fun(foo). Does matlab do a deep copy of foo and passes it to the function or does it just pass a pointer? Same question for the assignment return_foo = structure; and for returning return_foo to the caller.

Edit: And does that behavior change when the data held by the structure gets more 'complex', e.g. nested structures, arrays, ...

1 Answers1

1

Unless you use handle (object oriented matlab) there is nothing like a pointer in matlab. It behaves as if a deep copy of the data is passed. Details are explained here

Community
  • 1
  • 1
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • and it is the same, even if i nest multiple structures or do similar 'complex' structures? –  Mar 03 '15 at 09:01
  • 2
    That is not correct. Behind the scenes, Matlab copies only on write operations (see linked duplicate). For more behind the scenes, see [this answer](http://stackoverflow.com/a/1735997/232610) – Jonas Mar 03 '15 at 09:03
  • Wouldn't it be a shallow copy for objects containing handles? – knedlsepp Mar 03 '15 at 09:04
  • @knedlsepp: Matlab passes everything as shallow copy. On a write operation, any value object (including normal variables and structs) gets a deep copy made, and is modified. Any handle object remains a shallow copy and the original data is modified. – Jonas Mar 03 '15 at 09:08
  • @Jonas: I think of the lazy-copy-on-write more of an optimization step. The difference between a deep and a shallow copy if something contains a handle is however important. I haven't done much using user defined classes, so I don't know the answer, but from what I just read I guess it would be more exact to say: *Built-in data is always value-copied (which makes for a deep copy). A user defined `handle`-object will be reference-copied. If contained in a structure this makes for a shallow copy. In addition to that the copy-on-write optimization is implemented.* – knedlsepp Mar 03 '15 at 09:15
  • Ok. After your rephrasing of the answer I think it is more clear that you mean: For built-in types the behavior is deep copy. [But not for user defined `handle`-types, which will be shallow copies, no matter if inside a struct]. – knedlsepp Mar 03 '15 at 09:24
  • @knedlsepp: I assumed FirefoxMetzger has no interest in OOP matlab so I did not explain. Just mentioned it in case a different behaviour is needed. @ FirefoxMetzger: Behaviour doesn't change regardless how complex your data is. As Jonas Post explains, in most cases that's not a memory issue. – Daniel Mar 03 '15 at 09:27