please explain diag([rand(1,n-2) + 1, 1, 17])
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
John D'Errico
2019-7-13
编辑:John D'Errico
2019-7-13
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?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!