0

I just realized that the "=" operator in Julia acts more like a pointer for matrices than an assignment. For example, if I have a matrix A and I set a new matrix B with B=A, then any modification to B will also apply to A. Instead, I want to initialize B with A, but any changes that I make to B I do not want to apply to A. My current solution is to use Julia's copy() function, but it seems to take a non-negligible amount of time, and it seems like using copy() is a clunky solution. Any solutions/work-arounds would be greatly appreciated. Thank you!

I have a solution to my problem [copy()], but I assume there is a better solution out there.

Ron Snow
  • 13
  • 4
  • 3
    I imagine that it takes a non-negligible amount of time because it actually copies something. I also imagine (without knowing) that if there was a better solution X for copying, X would be named `copy`, and `copy` would be named differently. – mkrieger1 Dec 21 '22 at 22:23
  • If you want matrix `b` to be completely independent of matrix `a` then `deepcopy()` is needed. See here for details: [What is the difference between copy and deep copy in Julia?](https://stackoverflow.com/q/60017533/13843268). – sj95126 Dec 21 '22 at 23:14
  • 3
    @sj95126 `deepcopy` is *not* needed, unless the elements of the matrix are themselves mutable objects. For ordinary values you jus5 use `copy`. – DNF Dec 22 '22 at 00:09
  • @RonSnow It's difficult to understand from your post what you think is wrong with `copy`. To me it seems like the ideal solution, conceptually, and of course it should also be optimally efficient. Is it the name you don't like? – DNF Dec 22 '22 at 00:11
  • @DNF: Sorry, I should have been more specific. I was referring to the example in the link. – sj95126 Dec 22 '22 at 00:16
  • @DNF It seems like copy() is the best solution. I suppose I was assuming there would be a "better" way to do this through the use of an operator (i.e., := ). In my previous programming experience, the "=" operator NEVER acted as a pointer, so this just seemed odd to me. I guess I'll just need to make do with copy()! – Ron Snow Dec 22 '22 at 17:27
  • @mkrieger1 You bring up a good point :) – Ron Snow Dec 22 '22 at 17:27
  • @RonSnow In most languages it actually does act like that, also in Python and Matlab. But in Matlab there is a sneaky copy operation which happens when you modify `B`, but not otherwise. – DNF Dec 22 '22 at 18:04

1 Answers1

0

similar(A) creates the array without copying the values.

Tom
  • 16
  • So edit the question in a way that justifies this answer. The question is so ambiguous! Say you just wanted a similar independent matrix with the same dimension regardless of values! – Shayan Dec 22 '22 at 06:08
  • Thank you for suggesting this function. Unfortunately, I do want to copy the values. Apologies for the confusion. – Ron Snow Dec 22 '22 at 17:25