MATLAB: How to put output of a function in diagonal of matrix

diagonalfunctionmatrixoutput

how would i have a function output become the diagonal of a matrix, for instance
function y=f(x)
y= 3x+1;
end
how do i put the output of this function as the diagonal of a matrix with 0s everywhere else. i've attempted some type of for loop but it doesnt seem to work
i.e. the diagonal should have y(0), y(1), y(2),… y(n),
for different values of n

Best Answer

If y is a vector, then simply
y = diag(y);
If y is a matrix and you are trying to pick off the diagonal, then e.g.,
y = diag(diag(y));
Related Question