# # 1:end

24 views (last 30 days)
rovin singh on 16 Mar 2020
Edited: Stephen Cobeldick on 16 Mar 2020
[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

Bhaskar R on 16 Mar 2020
You need to use
g(sub2ind(size(g), r,c)) = 1

KSSV on 16 Mar 2020
idx = [2 5 7 8 9] ;
g = zeros(3) ;
g(idx) = 1 ;

Stephen Cobeldick on 16 Mar 2020
Edited: Stephen Cobeldick on 16 Mar 2020
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