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

如何在Matlab中通过索引矩阵实现指定位置的赋值操作?

Hey there! Let's break down your problem and work through solutions for both examples.


Second Example: Clear Row Mapping Rule

Looking at your second example, the pattern is straightforward and generalizable:

  • For each column j (from 1 to 4), the value index(j) maps directly to which row gets a 1:
    • Values 1 or 2 → set row 1 of column j to 1
    • Values 3 or 4 → set row 2 of column j to 1

You can simplify this mapping using ceil(index/2) to group index values into row numbers (1 or 2). Here's the clean MATLAB code to achieve your desired output:

% Initialize 2x4 zero matrix
A = zeros(2, 4);
% Define your index vector
index = [1 3 2 4];

% Identify which columns belong to each row
row1_cols = ceil(index ./ 2) == 1;
row2_cols = ceil(index ./ 2) == 2;

% Assign 1s to the correct positions
A(1, row1_cols) = 1;
A(2, row2_cols) = 1;

Running this code will produce exactly the matrix you want:

A =
     1     0     1     0
     0     1     0     1

First Example: Deriving the Underlying Rule

For your first example, let's map the desired A matrix back to the index vector to unpack the pattern:
Desired A:

A =
     1     1     0     0
     0     1     1     0

The 1s are at positions (1,1), (1,2), (2,2), (2,3). Looking at index = [1 2 2 3], the initial pattern seems a bit inconsistent at first glance:

  • index(j)=1: Only row 1 of column j gets a 1
  • index(j)=2: Both rows of column j get a 1 (column 2) OR only row 2 gets a 1 (column 3)
  • index(j)=3: No rows get a 1

A more consistent interpretation that aligns with most of your desired output is treating index(j) as a range indicator:

  • index(j)=1: Set row 1 only
  • index(j)=2: Set rows 1 and 2
  • index(j)=3: Set row 2 only (but since your desired column 4 is all zeros, maybe index(j)=3 means no assignment here?)

But this would set column 3's row 1 to 1, which doesn't match your desired result. To get exactly your first example's output, we'd need a minor adjustment for column 3—maybe a case-specific rule where index(j)=2 sets only row 2 when j>2. Here's code that does that:

A = zeros(2, 4);
index = [1 2 2 3];

for j = 1:length(index)
    k = index(j);
    switch k
        case 1
            A(1, j) = 1;
        case 2
            if j == 2
                A(:, j) = 1;
            else
                A(2, j) = 1;
            end
        case 3
            % Do nothing for column 4
    end
end

If there's a general rule you're following that I missed (e.g., index(j) indicates a sliding window of rows), feel free to clarify and we can refine the solution to be fully generalizable!


内容的提问来源于stack exchange,提问作者Duan Yu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:22:40