MATLAB Answers

Linear indices from row and column indices for a rectangular region of interest.

9 ビュー (過去 30 日間)
bayesianguy
bayesianguy 2019 年 6 月 14 日
コメント済み: Star Strider 2019 年 6 月 17 日
I have the row and column indices of a rectangular region of interest in a rectangular image. How can i get the linear indices from these row and column indices?
%this works
a = rand(5,5); %changed.
row_indices = 1:5;
col_indices = 1:5;
[X,Y] = meshgrid(row_indices,col_indices);
indices = sub2ind(size(a), Y, X)
%i want the indices when rows and cols are not necessarily of same length.
a = rand(5,3); %changed
row_indices = 1:5;
col_indices = 1:3;
[X,Y] = meshgrid(row_indices,col_indices);
indices = sub2ind(size(a), Y, X) %this would give out of range subscript.

  1 件のコメント

bayesianguy
bayesianguy 2019 年 6 月 16 日
I had made a mistake in the code snippet. Now it is edited.
When the size of matrix is 5 x 5, the row and column indices going from 1:5 can create a nice grid which works with sub2ind.
However, when i have a rectangular matrix of size 5 x 3, the grid elements are going to have elements like (5,5) which is out of range.

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

採用された回答

Star Strider
Star Strider 2019 年 6 月 16 日
You need to reverse the order of the second and third arguments to sub2ind:
indices = sub2ind(size(a), X(:), Y(:)) %this would give out of range subscript.
and ideally make them column vectors, using the (:) subscript notation.
Note that ndgrid may be preferable to meshgrid.

  2 件のコメント

bayesianguy
bayesianguy 2019 年 6 月 17 日
It works neatly with ndgrid than meshgrid.
The vectorized input was the key. Thanks a lot.
Star Strider
Star Strider 2019 年 6 月 17 日
As always, my pleasure.

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

その他の回答 (1 件)

KSSV
KSSV 2019 年 6 月 14 日
編集済み: KSSV 2019 年 6 月 14 日
YOu need to consider the size of matrix a.
%this works
a = rand(5,5);
row_indices = 1:5;
col_indices = 1:5;
[X,Y] = meshgrid(row_indices,col_indices);
indices = sub2ind(size(a), Y, X)
%i want the indices when rows and cols are not necessarily of same length.
row_indices = 1:5;
col_indices = 1:3;
a = rand(3,5) ;
[X,Y] = meshgrid(row_indices,col_indices);
indices = sub2ind(size(a), Y, X) %this would give out of range subscript.

  1 件のコメント

bayesianguy
bayesianguy 2019 年 6 月 16 日
I have made a mistake in the code snippet.
When the size of matrix is 5 x 5, the row and column indices going from 1:5 can create a nice grid which works with sub2ind.
However, when i have a rectangular matrix of size 5 x 3, the grid elements are going to have elements like (5,5) which is out of range.

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


Translated by