MATLAB: Please explain diag([rand(1,n-2) + 1, 1, 17])

diag functionrotation matrix

I came across the following function in one of your answers but couldn't understand it. please explain:
S=diag([rand(1,n-2) + 1, 1, 17])
How does it works? Also, as far as I know diag function can have maximum of two inputs, not three.
I tried my best to find it from tutorials and other help materials or PDFs available online about Matlab programming but couldn't get the answer.

Best Answer

When you have a problem, take it apart from the inside. What is inside-most? Was diag called with multiple inputs at all? (No.) Here is your line:
S=diag([rand(1,n-2) + 1, 1, 17])
Inside the call to diag, we see this:
[rand(1,n-2) + 1, 1, 17]
What do square brackets do? They concatenate things, here horizontally into a longer row vector.
So what does this do?
rand(1,n-2)
It creates a row vector, of random uniform elements. The size is 1x(n-2).
Then it adds 1 to those numbers.
Then it concatentates the numbers 1 and then 17 to the end of that vector.
For example:
n = 5;
[rand(1,n-2) + 1, 1, 17]
ans =
1.8147 1.9058 1.127 1 17
Finally, the vector, now of length n, is passed to diag.
Was diag ever called with more than 1 argument? NO.
Again, don't get confused at a long line of code. Break it apart. Think about what each piece does. Finally, learn how things like parens work. What do square brackets do?