3

For example, I want to do a deep copy of a to b:

>> a=zeros(2,3);
>> b=a;

So here = creates only a shallow copy. My question is, how to generate a deep copy in this case? I know that I can add a command like

b(1,1)=b(1,1)

to make it a deep copy. But is there a better way to do that?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
f. c.
  • 1,095
  • 11
  • 26
  • 2
    Please describe your use case. I fail to see the usefulness of this. You might be in danger of introducing a pessimization in your code. – Cris Luengo Jan 31 '20 at 15:17
  • The problem I had was, my matlab function called a C function which silently changed the values of input parameters that matlab was not aware of. – f. c. Feb 01 '20 at 18:31
  • Ah, but there you have an interesting question. Please [edit] the problem into your question, including a [mre] that shows how you call this function from MATLAB. There are different solutions depending on if you use a MEX-file or if you use the new method of automatically interfacing a C library. Explicitly forcing a deep copy is not the right approach IMO. – Cris Luengo Feb 01 '20 at 18:43
  • Or rather, write a new question, to not invalidate the answers you’ve gotten here. – Cris Luengo Feb 01 '20 at 18:49

2 Answers2

7

Matlab does not create a shallow copy, instead it uses copy on write. Except for the runtime, this should be totally transparent to you, meaning matlab creates the copy when required. Still if you want to force a copy, you could use one of the examples mentioned here: https://stackoverflow.com/a/36062575/2732801

 B=A(:,:);
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • 1
    Thanks. How about if A's dimension is changeable? I mean that A can be 3 dimensional array or 4 dimensional array. – f. c. Jan 31 '20 at 13:13
  • You can use linear indexing and then reshape to the original array size: `B = reshape(A(:), size(A))`. Note that you'll have to replace the `A(:)` with some operation that actually copies the underlying data if you want a "deep copy". – Andrew Janke Jan 31 '20 at 16:26
3

In general MATLAB uses copy on write and you shouldn't have to think about it. I agree with Daniel that this kind of copy is completely transparent to you, but I would not recommend doing a forced deep copy. Things like reshape will not force a copy either so you get a lot of efficiency in terms of memory usage. MATLAB will create a copy for you when it needs too.

Here are some good article discussing this:

Nick Haddad
  • 8,767
  • 3
  • 34
  • 38
  • 2
    The problem I had was, my matlab function called a C function which silently changed the values of input parameters that matlab was not aware of. – f. c. Feb 01 '20 at 18:30