# # 1:end

87 ビュー (過去 30 日間)
rovin singh 2020 年 3 月 16 日

[r,c]=ind2sub([3,3],[2,5,7,8,9])
output:
r = 2 2 1 2 3
c = 1 2 3 3 3
and while i am run following code then why this fill whole matrix
g(r(1:end),c(1:end))=1
its output should be according to me
0 0 1
1 1 1
0 0 1
but it produces
1 1 1
1 1 1
1 1 1

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

### 回答 (3 件)

Bhaskar R 2020 年 3 月 16 日
You need to use
g(sub2ind(size(g), r,c)) = 1
##### 0 件のコメント表示非表示 -1 件の古いコメント

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

KSSV 2020 年 3 月 16 日
idx = [2 5 7 8 9] ;
g = zeros(3) ;
g(idx) = 1 ;
##### 0 件のコメント表示非表示 -1 件の古いコメント

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

Stephen 2020 年 3 月 16 日

Explanation
"why this fill whole matrix"
g(r(1:end),c(1:end))=1
The MATLAB documentation explains "There is often confusion over how to select scattered elements from a matrix. For example, suppose you want to extract the (2,1), (3,2), and (4,4) elements from A. The expression A([2 3 4], [1 2 4]) won't do what you want." The documentation then demonstrates how that syntax should be interpreted, you should have a look.
Basically the entire column indexing applies to each individual row index (or equivalently the entire row indexing applies to each individual column index). Your understanding that correponding element pairs/triples/... of the index values are referenced is incorrect.
"its output should be according to me"
0 0 1
1 1 1
0 0 1
Nope. Lets follow the explanation in the MATLAB documentation. If it makes it easier to understand, you can split one of your example indices into repeated scalar indexing, e.g. your example is equivalent to
g = zeros(3,3);
g(r(1),c) = 1;
g(r(2),c) = 1;
g(r(3),c) = 1;
g(r(4),c) = 1;
g(r(5),c) = 1;
Which clearly results in g being all ones, because c has indices for all columns, and r has indices for all rows.
"but it produces"
1 1 1
1 1 1
1 1 1
because that is the correct interpretation of your indexing.
Solution
The page I linked to above also explains how to use linear indexing to get the result that you want:
idx = [2,5,7,8,9];
g = zeros(3,3);
g(idx) = 1

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

### Community Treasure Hunt

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

Start Hunting!

Translated by