Extract elements given a two-dimensional matrix of column indices per row from a two-dimensional matrix in MATLAB

I tried to repurpose my data from the matrix block that determined its indices. Hope this example can make it clear:

A=rand(18400,100);
A_IDX=randi([1 100],[18400 100]);

A_IDXconsists of 18,400 rows and 100 columns. I wanted to extract an Aindex matrix A_IDX. The result will be something like this:

A=[1 2 3; 4 5 6];
A_IDX=[1 3; 2 3];
A_Result=[1 3; 5 6];

I tried A(:,A_IDX), but it gave me a matrix size of 1840x184000, which I did not want to do in the first place. Can anybody help? Thanks in advance!

+4
source share
3 answers

, . , , bsxfun , , .

2D-

2D -

function out = take_cols(a, col_idx)

n = size(a,1);
lidx = bsxfun(@plus,(col_idx-1)*n,(1:n).');
out = a(lidx);

-

>> a
a =
    39    83    39    48    36
    58    74    20    19    50
    69    97    65    34    57
    47    58    80    24    51
>> col_idx
col_idx =
     2     4
     3     5
     1     4
     2     5
>> take_cols(a, col_idx)
ans =
    83    48
    20    50
    69    34
    58    51

2D-

2D -

function out = take_rows(a, row_idx)

[m,n] = size(a);
lidx = bsxfun(@plus,row_idx, (0:n-1)*m);
out = a(lidx);

-

>> a
a =
    39    83    39    48    36
    58    74    20    19    50
    69    97    65    34    57
    47    58    80    24    51
>> row_idx
row_idx =
     3     2     3     1     2
     4     3     4     2     4
>> take_rows(a, row_idx)
ans =
    69    74    65    48    50
    47    97    80    19    51
+7

, . , A .

A_IDX_aux=A_IDX';
reshape(A(sub2ind(size(A),repelem(1:size(A,1),1,size(A_IDX,1)).',A_IDX_aux(:))),[size(A,1), size(A_IDX,2)]).';
+2

, , Divakar Ander: )

:

res = cell2mat(arrayfun( @(x) A(x,A_IDX(x,:)), (1:size(A,1))', 'UniformOutput',false));

cell2mat, , , bsxfun, , , 3 . !

Elapsed time is 0.000058 seconds.   % Divakar
Elapsed time is 0.000077 seconds.   % Andres
Elapsed time is 0.000339 seconds.   % Me

bsxf ! ! . , - 'UniformOutput', false - , , .

:

  • bsxf - !

  • , , , .

  • : D , , -

+2

Source: https://habr.com/ru/post/1687368/


All Articles