Matrix position stored in a variable!

Suppose A=rand(10,10) and I need to access the following elements in A: A(2,3), A(4,5), A(6,7). If the positions are stored in a variable, d=[2 3; 4 5; 6 7], how the matrix elements can be retrieved?
Well, a simple solution is the following for loop.
for i = 1 : size(b, 1)
A(b(i,1), b(i,2))
end
Any better suggestion?

 採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 12 月 11 日

0 投票

A=magic(10);
d=[2 3; 4 5; 6 7];
B=A(sub2ind(size(A),d(:,1),d(:,2)))
Update for any size of d
A=rand(2,3,4);
d=[1 2 3;2,3,4;1,2,4];
[m,n]=size(d);
if ndims(A)~=n
error('Dimension mis-match');
end
ind=mat2cell(d,m,ones(1,n));
B=A(sub2ind(size(A),ind{:}))

3 件のコメント

Mohsen  Davarynejad
Mohsen Davarynejad 2011 年 12 月 11 日
Thanks Fangjun. I also do not know the dimentions, d can be n*m matrix were n and m are changind during the execution time. so I can not use arguments like d(:,1), d(:,2).
Fangjun Jiang
Fangjun Jiang 2011 年 12 月 11 日
That's tough! See update.
Mohsen  Davarynejad
Mohsen Davarynejad 2011 年 12 月 11 日
Just perfect! Thanks.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by