フィルターのクリア

How can I store the values of a diagonal using only a for loop?

3 ビュー (過去 30 日間)
Jonas Morgner
Jonas Morgner 2022 年 5 月 4 日
編集済み: Walter Roberson 2022 年 5 月 4 日
%A
rng('default')
r2 = randi(100,3,3); % Creating a 3x3 matrix, with random values from 1 to 100
%B
d = diag(r2) % Obtain the diagonal elements
%C
Metod1 = d(2,1) % Using two parameters (row 2, column 1)
Metod2 = d(3) % Using one parametr (3rd element)
How can I create a new vector which only stores the diagonal using a for loop from the initial matrix?

採用された回答

Walter Roberson
Walter Roberson 2022 年 5 月 4 日
If you loop from 1 to the minimum of the number of rows or columns, then for iteration K the element is at d(K,K)
If you want to use linear indexing, then note that once you know where one element of the diagonal is, that the next one is (rows + 1) elements further along. For example, 3 x 3, rows+1 is 4, and the diagonals are at (1), (1+4), (1+4+4)
  2 件のコメント
Jonas Morgner
Jonas Morgner 2022 年 5 月 4 日
First of all thak you fo the explanation, I now can understand this in theroy. However I am really new to programming and I dont know how to translate this into code. Could you help me with that?
Walter Roberson
Walter Roberson 2022 年 5 月 4 日
編集済み: Walter Roberson 2022 年 5 月 4 日
for K = 1 : size(d,1)
d(K,K)
end
after that it becomes a matter of how to store the K'th value into the K'th element of a vector. If that is not something you are familiar with you should be considering running through MATLAB Onramp.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by