Use Indexing for more than 1 dimension of array simultaneously

4 次查看(过去 30 天)
I have a 10 by 3 matrix:
matrix = rand(10, 3);
I have an indexing array which selects a column number for each row:
idx = [1; 2; 2; 3; 1; 2; 1; 2; 3; 3];
I want to produce a 10x1 array which uses the above index array to extract the respective column number element at each row. Without using a for loop.
I have tried:
output = matrix(1:10, idx)
output = 10×10
0.2039 0.6450 0.6450 0.8811 0.2039 0.6450 0.2039 0.6450 0.8811 0.8811 0.3955 0.0347 0.0347 0.1645 0.3955 0.0347 0.3955 0.0347 0.1645 0.1645 0.5710 0.9536 0.9536 0.9736 0.5710 0.9536 0.5710 0.9536 0.9736 0.9736 0.5103 0.9297 0.9297 0.2534 0.5103 0.9297 0.5103 0.9297 0.2534 0.2534 0.0723 0.4962 0.4962 0.0039 0.0723 0.4962 0.0723 0.4962 0.0039 0.0039 0.1273 0.1957 0.1957 0.3339 0.1273 0.1957 0.1273 0.1957 0.3339 0.3339 0.0603 0.7878 0.7878 0.9416 0.0603 0.7878 0.0603 0.7878 0.9416 0.9416 0.0832 0.5866 0.5866 0.9793 0.0832 0.5866 0.0832 0.5866 0.9793 0.9793 0.5630 0.3352 0.3352 0.9332 0.5630 0.3352 0.5630 0.3352 0.9332 0.9332 0.7188 0.8864 0.8864 0.6835 0.7188 0.8864 0.7188 0.8864 0.6835 0.6835
This produces a 10x10 matrix.

回答(3 个)

Fangjun Jiang
Fangjun Jiang 2023-7-25
编辑:Fangjun Jiang 2023-7-25
matrix(sub2ind(size(matrix),(1:10)',idx))

the cyclist
the cyclist 2023-7-25
You can use linear indexing:
matrix = rand(10, 3);
idx = [1; 2; 2; 3; 1; 2; 1; 2; 3; 3];
linearIndex = sub2ind(size(matrix),1:10,idx');
matrix(linearIndex)
ans = 1×10
0.8064 0.6649 0.2393 0.9216 0.0166 0.3291 0.6957 0.8769 0.4766 0.2352

James Tursa
James Tursa 2023-7-25
编辑:James Tursa 2023-7-25
Yet another way using linear indexing (showing what sub2ind( ) does internally):
matrix = rand(10, 3);
idx = [1; 2; 2; 3; 1; 2; 1; 2; 3; 3];
m = size(matrix,1);
matrix( (1:m)' + m*(idx-1) )
ans = 10×1
0.8923 0.3166 0.8492 0.0101 0.2614 0.4642 0.7455 0.5160 0.9367 0.5664
And to show that it is the same as other solutions:
matrix(sub2ind(size(matrix),(1:m)',idx))
ans = 10×1
0.8923 0.3166 0.8492 0.0101 0.2614 0.4642 0.7455 0.5160 0.9367 0.5664
  1 个评论
Walter Roberson
Walter Roberson 2023-7-25
Note that linear indexing is what happens internally when you use sub2ind: sub2ind is a helper function to make it easier to calculate the correct linear indexing.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by