Is it possible to extract the values with a vector of indices for each row without using the for statement from the matrix?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Danny
am 17 Jun. 2020
Kommentiert: Ameer Hamza
am 17 Jun. 2020
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?
0 Kommentare
Akzeptierte Antwort
Ameer Hamza
am 17 Jun. 2020
Bearbeitet: Ameer Hamza
am 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
2 Kommentare
Weitere Antworten (1)
KSSV
am 17 Jun. 2020
Bearbeitet: KSSV
am 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
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!