Subscript to linear index

Asked by At

M is a matrix of prime numbers from 1 to 23 (in row order)

I don't understand how the second code line replaces the diagonal entries of M with 1. I am also confused because the function sub2ind converts row/column subscript to linear index both of which has nothing to do with the value of the entry.

M = zeros(3); M(:) = primes(23); M = M'
M(sub2ind(size(M), 1:3, 1:3)) = 1

1 Answers

2
Eliahu Aaron On

sub2ind(size(M), 1:3, 1:3) returns an array [1, 5, 9] of the linear index of entries: (1,1), (2,2), (3,3). In M(sub2ind(size(M), 1:3, 1:3)) you are accessing M as a vector, it is equivalent to writing M([1, 5, 9]) so you are accessing the matrix with linear indexing, and you are assigning the value 1 to those entries: M(sub2ind(size(M), 1:3, 1:3)) = 1 so that changes the value of those entries