Find items of a matrix using a per-column index

4 Ansichten (letzte 30 Tage)
SHC
SHC am 27 Jan. 2025
Beantwortet: Anton Kogios am 27 Jan. 2025
If
A = [1, 2, 3;
4, 5, 6]
and I have a per-column index.
idx = [2, 2, 1]
I want to find the items of A with the per-column index.
So the result I want is:
[4, 5, 3]
I know this can be done with a for loop, however, is there a way to do this without using loops?

Akzeptierte Antwort

Anton Kogios
Anton Kogios am 27 Jan. 2025
A = [1, 2, 3; 4, 5, 6];
idx = [2, 2, 1];
linearIndices = sub2ind(size(A), idx, 1:length(idx));
result = A(linearIndices)
result = 1×3
4 5 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by