# 1:end
조회 수: 107 (최근 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!