You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Julia中2D矩阵元素分配方案扩展至高维矩阵?

High-Dimensional Matrix Element Assignment (3D+)

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)):

  1. Initialize Matrix3: We first create a zero matrix with the same size as Matrix2 and element type as Matrix1—wrapping this in parentheses lets us chain the assignment directly.
  2. Target Indices: [Matrix2] grabs all linear indices where Matrix2 has a true (non-zero) value. For your 3D case, this will collect all valid positions across each of the 4 first-axis slices.
  3. Flatten Matrix1:
    • vec(Matrix1) flattens Matrix1 using 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.
  4. Assign Elements: The .= broadcast assignment fills Matrix3's target positions with the flattened elements from Matrix1, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:47:40