arraysalgorithmmatlabnested-loopsdiagonal

Populate the Diagonal Elements of An Array MATLAB


I have the following matrix C that I would like to recreate in MATLAB:

enter image description here

In this case uppercase C is an N = 3 by N = 3 matrix, but I would like to generate C for any size of N by N.

I randomly create random values for c on the interval 1 to 20 using:

N = 3
c =  randi([1,20],N+1,1,"double");

I initially thought that I could use nested for loops as follows:

function C = carray(c,N)
    C = zeros(N,N)
    for i =1:1:N
        for j=1:1:N
            if isdiag(C(i,j))
                C(i,j) = c(i) + c(i+1)
            end
        end
    end
end

However, this does not produce the desired result. Do I have to do this using diag() or spdiag()?


Solution

  • If you wish, you can do this in a single expression simply by using diag on the vector of the sum of the adjacent elements, like this:

    >> C = diag(c(1:end-1) + c(2:end))
    C =
        36     0     0
         0    22     0
         0     0    22