フィルターのクリア

How to index a matrix with existing array?

49 ビュー (過去 30 日間)
Xiaohan Du
Xiaohan Du 2017 年 11 月 3 日
編集済み: Stephen23 2017 年 11 月 3 日
Hi all,
Imagine there is a m by m matrix, I'd like to extract the [p, q] element, while [p, q] is the output of some calculations. For instance:
K>> a = rand(3)
a =
0.88517 0.098712 0.67973
0.91329 0.26187 0.13655
0.79618 0.33536 0.72123
K>> b = [2 3]
b =
2 3
K>> a(b)
ans =
0.91329 0.79618
Here b is the location, which should be the 2nd row, 3rd column. However, here Matlab gives the 2nd and 3rd element by column indexing. What I want is 0.13655.
I know I can use:
K>> a(b(1), b(2))
ans =
0.13655
But this is manual, my matrix may have random dimension, so I prefer something like a(b), any ideas?

採用された回答

Stephen23
Stephen23 2017 年 11 月 3 日
編集済み: Stephen23 2017 年 11 月 3 日
Simply use num2cell and sub2ind, then indices are not required:
>> c = num2cell(b);
>> a(sub2ind(size(a),c{:}))
ans = 0.13655
  1 件のコメント
Xiaohan Du
Xiaohan Du 2017 年 11 月 3 日
true MVP.

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

その他の回答 (1 件)

KL
KL 2017 年 11 月 3 日
編集済み: KL 2017 年 11 月 3 日
use sub2ind
[row, col] = sub2ind(size(a),b(:,1),b(:,2))
or directly
a(sub2ind(size(a),b(:,1),b(:,2)))
  2 件のコメント
Xiaohan Du
Xiaohan Du 2017 年 11 月 3 日
No, the manual index is what i'm trying to avoid, i.e. there cannot be:
b(:, 1), b(:, 2)
Xiaohan Du
Xiaohan Du 2017 年 11 月 3 日
Steve's answer is correct, but thanks anyway.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by