using a value to find index in a matrix?

3 ビュー (過去 30 日間)
Axel Yantosca
Axel Yantosca 2020 年 10 月 22 日
コメント済み: Walter Roberson 2020 年 10 月 22 日
How would one find the location inside a matrix? In this case I am looking for x, assuming it exists.
Matrix_A = randi([1 100],100,100)
x = randi ([1,100], 1)

採用された回答

Stephen23
Stephen23 2020 年 10 月 22 日
編集済み: Stephen23 2020 年 10 月 22 日
The simplest solution is to simply check for equality:
idx = x==Matrix_A;
which will return a logical array with true in every location where the value x occurs in that matrix.
If you want to convert that info to subscript indices, then you can use find on that logical array:
[R,C] = find(idx)
In many cases using a logical index is simpler and more efficient, but it really depends entirely on what you are going to do with these indices, which so far you have not explained.

その他の回答 (2 件)

David Hill
David Hill 2020 年 10 月 22 日
[i,j]=ind2sub(size(Matrix_A),find(Matrix_A==x));
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 10 月 22 日
You might as well just use
[i, j] = find(Matrix_A == x)
There is a role for using ind2sub(), but really not until you are working in more than 2 dimensions.

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


Walter Roberson
Walter Roberson 2020 年 10 月 22 日
Like I replied to your other question that was essentially the same, use
ismember(x, Matrix_A)
If you are trying to find where in the matrix it occurs, then use the second output of ismember().
This assumes that there is only one match. If there might be multiple matches then you might as well use
[row, column] = find(Matrix_A == x)

カテゴリ

Help Center および 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