# # 1:end

조회 수: 129(최근 30일)
rovin singh 2020년 3월 16일
편집: Stephen 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개)

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일
편집: 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!