Is it possible to extract the values with a vector of indices for each row without using the for statement from the matrix?

5 views (last 30 days)
Consider the following example.
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]; % reference matrix
b = [2; 1; 1; 3]; % index for each row that I want to extract
for i=1:size(A,1)
y(i,1) = A(i,b);
end
I am using the above code to extract values that I want.
Is there any simple function to implement the above script fast?

Accepted Answer

Ameer Hamza
Ameer Hamza on 17 Jun 2020
Edited: Ameer Hamza on 17 Jun 2020
see sub2ind()
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]; % reference matrix
b = [2; 1; 1; 3]; % index for each row that I want to extract
idx = sub2ind(size(A), 1:size(A,1), b.');
A(idx)
Result
>> A(idx)
ans =
2 4 7 12

More Answers (1)

KSSV
KSSV on 17 Jun 2020
Edited: KSSV on 17 Jun 2020
May be you are looking for
A(b,:)
The other
A(:,b)
will work, but in your case b has number 4 and in A there are only 3 columns.
To extract a complete row or column, : can be use
A(1,:) % picks the 1st row and all columns
A(:,3) % picks the allrows and third column
A(2,3) % pciks the second row and third column
  1 Comment
Danny
Danny on 17 Jun 2020
That is my typo, so I correct it.
However, I've already done above, but this is not working in my the latest version of Matlab.
>> piset
piset =
9 10 6 7 8 4 5 3 2 1
7 8 5 10 6 4 9 3 2 1
9 10 8 6 7 4 3 5 2 1
7 9 8 6 5 10 3 4 2 1
7 6 9 10 5 8 3 4 2 1
7 10 9 4 5 6 8 2 3 1
10 5 9 6 7 4 8 2 3 1
10 9 8 7 4 5 6 3 2 1
8 10 6 9 7 5 4 2 3 1
9 7 10 6 4 5 8 1 2 3
8 5 9 7 4 10 3 6 2 1
7 9 6 10 8 3 4 5 2 1
6 8 10 7 9 4 5 3 2 1
7 8 6 3 2 10 9 5 4 1
9 5 7 6 10 8 2 3 4 1
>> lset
lset =
8
7
7
2
3
3
9
2
4
10
3
6
5
7
1
>> piset(:,lset)
ans =
3 5 5 10 6 6 2 10 7 1 6 4 8 5 9
3 9 9 8 5 5 2 8 10 1 5 4 6 9 7
5 3 3 10 8 8 2 10 6 1 8 4 7 3 9
4 3 3 9 8 8 2 9 6 1 8 10 5 3 7
4 3 3 6 9 9 2 6 10 1 9 8 5 3 7
2 8 8 10 9 9 3 10 4 1 9 6 5 8 7
2 8 8 5 9 9 3 5 6 1 9 4 7 8 10
3 6 6 9 8 8 2 9 7 1 8 5 4 6 10
2 4 4 10 6 6 3 10 9 1 6 5 7 4 8
1 8 8 7 10 10 2 7 6 3 10 5 4 8 9
6 3 3 5 9 9 2 5 7 1 9 10 4 3 8
5 4 4 9 6 6 2 9 10 1 6 3 8 4 7
3 5 5 8 10 10 2 8 7 1 10 4 9 5 6
5 9 9 8 6 6 4 8 3 1 6 10 2 9 7
3 2 2 5 7 7 4 5 6 1 7 8 10 2 9
>>

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!