I tried to resample my data from a block of matrix that defined its indices. Hopefully this example can make it clear:
A=rand(18400,100);
A_IDX=randi([1 100],[18400 100]);
A_IDX
consist 18400 rows and 100 columns. I wanted to extract the matrix A
at the A_IDX
indices. Result would be something like:
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 that gave me 1840x184000 matrix size, which is not what I wanted to do in the first place. Anyone can help? Thanks in advance!
We could get the linear index equivalent for those indices and then simply indexing into the input array would give us the desired output. Now, to get those linear indices, we would make use of bsxfun
for the math computations related to the index computations, which would basically involve scaling and offsetting.
Indexing with 2D array of column indices
For a 2D
array of column indices, we would have -
function out = take_cols(a, col_idx)
n = size(a,1);
lidx = bsxfun(@plus,(col_idx-1)*n,(1:n).');
out = a(lidx);
Sample run -
>> 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
Indexing with 2D array of row indices
For a 2D
array of row indices, it would be -
function out = take_rows(a, row_idx)
[m,n] = size(a);
lidx = bsxfun(@plus,row_idx, (0:n-1)*m);
out = a(lidx);
Sample run -
>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With