Octave/MATLAB:无循环实现通过矩阵访问矩阵元素
Hey there! You can easily get your desired result without any loops by leveraging MATLAB's powerful indexing capabilities. Here are two straightforward approaches:
Approach 1: Use sub2ind (Most Readable)
The sub2ind function converts row-column indices into linear indices, which is perfect for your use case where you need to pick one element per row at the column specified in columns.
First, define your input matrices:
columns = [1,3,2,4]; WhichSet = [2, 2, 1, 2; 1, 1, 2, 1; 1, 2, 1, 2; 2, 1, 2, 2];
Then run this code:
% Generate row indices (1 to the number of rows in WhichSet) row_idx = 1:size(WhichSet, 1); % Convert row-column pairs to linear indices linear_idx = sub2ind(size(WhichSet), row_idx, columns); % Extract the elements using linear indices result = WhichSet(linear_idx);
Running this will give you result = [2, 2, 2, 2] exactly as you need.
Approach 2: Direct Linear Index Calculation (More Concise)
If you prefer a one-liner, you can calculate the linear indices manually using MATLAB's linear index formula: for a matrix A, the linear index of element A(i,j) is i + (j-1)*size(A,1).
Here's the code:
result = WhichSet((1:4)' + (columns - 1)*size(WhichSet,1));
This works by converting the row indices to a column vector, then adding the column offset (calculated from columns) multiplied by the number of rows in WhichSet. The result is an array of linear indices that we use to extract the desired elements.
Both methods are fully vectorized (no loops) and will efficiently produce your target output.
内容的提问来源于stack exchange,提问作者Santosh Kr

