How can I store the whole diagonal and not only the first element (For loop)

9 ビュー (過去 30 日間)
Jonas Morgner
Jonas Morgner 2022 年 5 月 8 日
コメント済み: VBBV 2022 年 5 月 8 日
% Part 3.1: Diagonal
%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)
%D
for K = 1 : size(d,1)
d(K,K)
end
I have a problem in storing the diagonal values of the Matrix. It somehow only stores the first entry of the diagonal, where instead it should store 3 entries in total. How can I change the for loop so it also stores the rest of the entries?
Also I get this error message when using the for loop:
"Index in position 2 exceeds array bounds. Index must not exceed 1"
What does it mean and how can I fix this?

採用された回答

VBBV
VBBV 2022 年 5 月 8 日
% Part 3.1: Diagonal
%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
d = 3×1
82 64 96
%C
Metod1 = d(2,1) % Using two parameters (row 2, column 1)
Metod1 = 64
Metod2 = d(3) % Using one parametr (3rd element)
Metod2 = 96
%D
for K = 1 : size(d,1)
D(K,K) = d(K); % d matrix has only 3 rows , 1 col
end
D % declare/assign a new matrix which stores all elements of d into D diagonally.
D = 3×3
82 0 0 0 64 0 0 0 96
  2 件のコメント
Jonas Morgner
Jonas Morgner 2022 年 5 月 8 日
Awesome Thank you very much! Unfortunately, I forgot to add that I need to store it in a 1x3 or 3x1 vector. How would the code differ if I want to store it in this specific new vector?
VBBV
VBBV 2022 年 5 月 8 日
You can simply use
D = d; % With out using loop
for K = 1 : size(d,1)
D(K,1) = d(K); % using loop
end

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

その他の回答 (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