如何将Julia中2D矩阵元素分配方案扩展至高维矩阵?
Got it, let's adapt your clever 2D matrix assignment line to work seamlessly with 3D (and higher-dimensional) arrays—while keeping it concise, just like you asked!
One-Line Solution (Default Julia Column-Priority Order)
This works for any dimension where the first axis of Matrix1 and Matrix2 are the same length, and the total number of non-zero elements in Matrix2 matches the total number of elements in Matrix1:
(Matrix3 = zeros(eltype(Matrix1), size(Matrix2)))[Matrix2] .= vec(Matrix1)
One-Line Solution (Matching Your Original 2D Row-Priority Order)
If you want to preserve the exact element ordering from your original 2D code (which uses transposition to get row-priority flattening), use this version to reverse the dimension order before flattening:
(Matrix3 = zeros(eltype(Matrix1), size(Matrix2)))[Matrix2] .= vec(permutedims(Matrix1, reverse(1:ndims(Matrix1))))
How It Works
Let's break down the logic using your 3D example (Matrix1: (4,6,6), Matrix2: (4,12,12)):
- Initialize Matrix3: We first create a zero matrix with the same size as
Matrix2and element type asMatrix1—wrapping this in parentheses lets us chain the assignment directly. - Target Indices:
[Matrix2]grabs all linear indices whereMatrix2has atrue(non-zero) value. For your 3D case, this will collect all valid positions across each of the 4 first-axis slices. - Flatten Matrix1:
vec(Matrix1)flattensMatrix1using Julia's default column-priority order (traversing the first axis fastest, then second, then third).- The permuted version reverses the dimension order before flattening, matching the row-priority behavior of your original
Matrix1'[:]in 2D.
- Assign Elements: The
.=broadcast assignment fillsMatrix3's target positions with the flattened elements fromMatrix1, maintaining alignment with the first axis.
Example Verification
Let's test the column-priority version with your 3D setup:
# Create test arrays Matrix1 = reshape(1:4*6*6, 4,6,6) # 4×6×6 array with elements 1-144 Matrix2 = falses(4,12,12) # Mark 6×6 regions in each first-axis slice of Matrix2 for i in 1:4 Matrix2[i, 1:6, 1:6] .= true end # Run the one-liner (Matrix3 = zeros(eltype(Matrix1), size(Matrix2)))[Matrix2] .= vec(Matrix1) # Validate the result @assert Matrix3[1, 1:6, 1:6] == Matrix1[1, :, :] @assert Matrix3[4, 1:6, 1:6] == Matrix1[4, :, :]
This approach scales to any number of dimensions beyond 3—just keep the first axis aligned between Matrix1 and Matrix2, and ensure Matrix2 has exactly as many non-zero positions as Matrix1 has elements.
内容的提问来源于stack exchange,提问作者chupa_kabra

