如何在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 valueindex(j)maps directly to which row gets a 1:- Values 1 or 2 → set row 1 of column
jto 1 - Values 3 or 4 → set row 2 of column
jto 1
- Values 1 or 2 → set row 1 of column
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 columnjgets a 1index(j)=2: Both rows of columnjget 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 onlyindex(j)=2: Set rows 1 and 2index(j)=3: Set row 2 only (but since your desired column 4 is all zeros, maybeindex(j)=3means 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

