please explain diag([rand(1,n-2) + 1, 1, 17])

2 ビュー (過去 30 日間)
Adnaan
Adnaan 2019 年 7 月 13 日
コメント済み: Adnaan 2019 年 7 月 14 日
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.

採用された回答

John D'Errico
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?
  1 件のコメント
Adnaan
Adnaan 2019 年 7 月 14 日
Thanks for helping me out.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by