How do I index into a 2D matrix using two equal length R and C vectors?

20 Ansichten (letzte 30 Tage)
I have a 2D matrix rho, and two vectors of indices R and C. How do I use R and C to index into rho?
>> rho=d
rho =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> R=[1 2]; C=[ 2 3];
i.e I want to obtain rho(R(1), C(1) ..etc

Akzeptierte Antwort

Ashish Uthama
Ashish Uthama am 7 Jul. 2011
You can use a combination of linear indexing and the function sub2ind to index into rho:
>> rho=d
rho =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> R=[1 2]; C=[ 2 3];
>> ind = sub2ind(size(rho), R, C);
>> rho(ind)
ans =
2 10

Weitere Antworten (1)

Sean de Wolski
Sean de Wolski am 7 Jul. 2011
Or:
rho = magic(4);
R=[1 2]; C=[ 2 3];
diag(rho(R,C))
runs much faster for smaller R,C but much longer for big ones...

Kategorien

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

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by