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

Octave/MATLAB:无循环实现通过矩阵访问矩阵元素

Solution for Vectorized Indexing in 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:00:43