access the elements in a matrix given the column indexes

For example x = [1 2 3 4; 5 6 7 8; 9 10 11 12]
Given the row indexes vector y = [1 3 4]; I'd like to get the associated elements : x(1, y(1)) = 1, x(2, y(2)) = 7, x(3, y(3)) = 12. [1 7 12]
Don't use loop.
THanks

답변 (2개)

dpb
dpb 2013년 8월 15일
편집: dpb 2013년 8월 15일
iy=[1 3 4];
ix=[1:length(iy)];
y=x(sub2ind(size(x),ix',iy');

댓글 수: 2

I believe that first line is not valid Matlab syntax.
typo, yes...should be obvious. Corrected, thanks.

댓글을 달려면 로그인하십시오.

Jan
Jan 2013년 8월 15일
how about
diag( x(:, y) )

댓글 수: 4

doesn't work for y = [1 2 4];
Jan
Jan 2013년 8월 15일
편집: Jan 2013년 8월 15일
result for diag( x(:, [1 2 4]) ) is [1 6 12]'
y(1) is 1 -> x(1, 1) is 1
y(2) is 2 -> x(2, 2) is 6
y(3) is 4 -> x(3, 4) is 12
maybe I didn't quite get your question, to me it looks correct?
Yes, you're right. I'm just curious why does this work? can you give a little bit more explanation?
in x(:, y) the colon operator returns all rows of the matrix x. the second argument 'y' does 'column selection', i.e. it picks only the interesting columns from x:
x(:, [1 2 4])
ans =
1 2 4
5 6 8
9 10 12
the values you are looking for obviously appear as diagonal elements in the result and can be extracted with the diag() function.
the reason why the intersting values are on the diagonal is pretty simple, allthough I admit, that one might must give it a second thought :)
I hope that helped!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2013년 8월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by