Julia数组变量赋值疑问:修改元素与重新赋值为何结果不同
Great question! This is a common point of confusion when working with mutable objects like arrays in Julia, so let's break it down clearly.
What's happening when you do B = A?
When you run B = A right after creating A = [1. 2; 3 4], you're not making a copy of the array. Instead, you're telling Julia: "let the variable B refer to the exact same array object that A is pointing to."
Think of it like two people holding a link to the same shared document. If one person edits the document's content (like changing A[1,1] = 7), the other person (looking via B) will see those changes immediately—because they're both accessing the same underlying data.
You can verify this with Julia's === operator, which checks if two variables refer to the same object:
A = [1. 2; 3 4] B = A println(A === B) # Output: true (same object)
Why doesn't A = ones(2,2) change B?
When you run A = ones(2,2), you're not modifying the original array at all. Instead, you're doing two things:
- Creating an entirely new array filled with ones (
ones(2,2)makes a fresh 2x2 array). - Reassigning the variable
Ato point to this new array.
The variable B is still pointing to the original array we created first. It doesn't care that A switched to a new object—B's reference never changed. Using === again shows this:
A = ones(2,2) println(A === B) # Output: false (different objects now)
How to make a copy if you want independent arrays
If you want B to be a separate array that doesn't change when you modify A, use the copy() function (for shallow copies, which works for simple arrays like your example) or deepcopy() (for arrays with nested mutable objects):
A = [1. 2; 3 4] B = copy(A) # Create a separate copy A[1,1] = 7 println(B) # Output: [1.0 2.0; 3.0 4.0] (unchanged!)
Quick recap
B = A: VariablesAandBreference the same mutable array object. Modifying the object's contents affects both.A = ones(2,2): VariableAis rebound to a new array object.Bstill references the original array, so its contents don't change.
内容的提问来源于stack exchange,提问作者Jeff

