# 1:end
104 ビュー (過去 30 日間)
古いコメントを表示
[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
explain please
0 件のコメント
回答 (3 件)
Stephen23
2020 年 3 月 16 日
編集済み: Stephen23
2020 年 3 月 16 日
"explain please"
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
Read the documentation!
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!