Search code examples
matlabdiagonal

Create diagonal matrix without using MATLAB built-in functions


I know the answer to this question as shown below.

function a = reverse_diag(n)
    b = zeros(n);
    b(1:n+1:end) = 1;
    a(1:n, n:-1:1) = b(1:n, 1:n);
end

But why does it look like that? What does this mean?

b(1:n+1:end) = 1;

Solution

  • I seem to recall seeing something similar to this in MATLAB answers very recently, hence I will be brief.

    MATLAB arrays can be indexed in 2 relevant ways:

    1. Like A(x,y) using the actual coordinates in the matrix.

    2. Like A(index), no matter how many dimensions the matrix A actually has. This is called linear indexing and will go through the matrix column by column. So for a 10x10 matrix, A(11) is actually A(2,1).

    Read up on ind2sub and sub2ind to get a sense of how these work. You should now be able to figure out why that line works.