How to index the values of an array using a series of rows, column indices?

15 ビュー (過去 30 日間)
Bill Tubbs
Bill Tubbs 2021 年 7 月 9 日
コメント済み: Bill Tubbs 2021 年 7 月 10 日
Couldn't find an answer about this and it is not mentioned in the Matlab documentation page on array indexing.
I want to know how to read (or assign to) a set of values in an array using a series of positions (row, col).
For example, suppose my array is
rng(0); A = randi(9, 4, 6)
A =
8 6 9 9 4 6
9 1 9 5 9 1
2 3 2 8 8 8
9 5 9 2 9 9
and I want to retrieve three values from some arbitrary positions such as (3, 2), (3, 3), and (4, 3).
I figured out I can do it this way, but is this the correct/best way?
my_pts = [3 2; 3 3; 4 3];
A(sub2ind(size(A),my_pts(:,1),my_pts(:,2)))
ans =
3
2
9
or
A(sub2ind(size(A),my_pts(:,1),my_pts(:,2))) = [0 0 0]
A =
8 6 9 9 4 6
9 1 9 5 9 1
2 0 0 8 8 8
9 5 0 2 9 9
  3 件のコメント
Stephen23
Stephen23 2021 年 7 月 10 日
SUB2IND is the best way.
Bill Tubbs
Bill Tubbs 2021 年 7 月 10 日
Thank you.

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

回答 (1 件)

Scott MacKenzie
Scott MacKenzie 2021 年 7 月 9 日
If you want to pull those three values from A and concatenate them, as in your output, then just retrieve the three elements using row-column indexing in A and concatenate the values using brackets:
A = randi(9, 4, 6)
A = 4×6
2 4 3 3 1 1 4 1 7 2 8 4 1 4 6 3 8 4 1 8 2 3 6 4
[A(3,2) A(3,3) A(4,3)]
ans = 1×3
4 6 2
  3 件のコメント
Scott MacKenzie
Scott MacKenzie 2021 年 7 月 10 日
It's a bit unclear what you might mean by index arbitrary points programmatically. If you know A is a 4x6 matrix, then here's an indexed arbitrary point from A which is generated programmatically:
arbitraryRow = randi(4,1);
aribtraryCol = randi(6,1);
arbitraryPoint = A(arbitraryRow, arbitraryCol);
If you want points -- plural -- then put this in loop and add the points to a vector, or something like that. Good luck.
Bill Tubbs
Bill Tubbs 2021 年 7 月 10 日
編集済み: Bill Tubbs 2021 年 7 月 10 日
By arbitrary points I meant variable. I can see how it could be done with a for loop but I was looking for a MATLAB equivalent of this Python (Numpy) code where my_pts is a variable which could have any values:
In [1]: my_pts = ([2, 2, 3], [1, 2, 2])
In [2]: A[my_pts]
Out[2]: array([4, 6, 2])
I modified the question to make this more clear.

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

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by