I have a matrix of variable dimension and would like to access it with an index stored in a variable, something like this:
matrix = [1, 2; 3, 4; 5, 6]
idx = [3, 1]
elem = matrix(idx) % should result in access to element (3, 1) => 5
Of course, this does not work and will instead get element numbers 3 and 1 (which have values 3 and 1 in that case).
I know sub2ind, but that does not help either, since the number of dimensions is variable. Is there a built-in solution for my problem or will I have to write an access method by myself? (It's not too difficult, but a built-in solution would be preferable.)

댓글 수: 1

Mikhail
Mikhail 2014년 11월 5일
Yeah, I don't know simple solution too.

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

 채택된 답변

Guillaume
Guillaume 2014년 11월 5일

1 개 추천

You can use cell expansion to comma separated list to index your matrix. So first convert your index matrix into a cell array, then convert the cell array into a list:
c = num2cell(idx);
matrix(c{:}); %expand c into comma separated list

댓글 수: 5

Michael B.
Michael B. 2014년 11월 5일
I think this is what I'm looking for. However, it would be nice if Matlab would provide a more smoothly integrated solution with no need for an extra line of code.
Mikhail
Mikhail 2014년 11월 5일
matrix(num2cell(idx){:}) - 1 line
Mikhail
Mikhail 2014년 11월 5일
doesn't work this way, sorry
I agree. Unfortunately, the way matlab is designed prevents any simpler method.
Saying that, you can always write your own helper function based on this:
function v = matindex(matrix, vecidx)
%MATINDEX use vector vecidx as an nD index intro matrix to return value v
cidx = num2cell(vecidx);
v = matrix(cidx{:});
end
Michael B.
Michael B. 2014년 11월 6일
And that's exactly why I wonder even more about the lack of a built-in way to do it - it would be so simple.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2014년 11월 5일

댓글:

2014년 11월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by