Variables in matrix not updating from for loop

12 ビュー (過去 30 日間)
Nolan Ames
Nolan Ames 2021 年 6 月 22 日
コメント済み: Nolan Ames 2021 年 6 月 22 日
I am currently using a for loop in order to find the maximum eigenvalues of a matrix. The loop is as follows
for k = 0:c
e = eig(z)
M = max(e)
x = [x,M]
k = k+1
end
The variable k begins at 0, and the loop runs until c, a count of 50. z is the following 4x4 matrix: [k 0 2 0; 0 k 0 2; 3 4 5 0; 4 3 0 5]. What I am attempting to do is extract the maximum eigenvalue from the matrix, add it to an array x , then add 1 to k within the matrix, and continue until c is reached. However, k within the matrix is not updating, so it is simply finding the same eigenvalue 50 times. The k working the counter is performing as expected, but what do I have to do in order to make the k within the matrix update at each step as well?
  2 件のコメント
Scott MacKenzie
Scott MacKenzie 2021 年 6 月 22 日
編集済み: Scott MacKenzie 2021 年 6 月 22 日
It would help if you provided all the code so it can be excuted to produce the error.
But, note that this line
k = k+1;
has no bearing on "k within the matrix".
Furthermore, k is the loop index variable in your for-loop, so it cannot be changed within the loop. So, there are a few issues to resolve.
Nolan Ames
Nolan Ames 2021 年 6 月 22 日
That is all the code. If you're reffering to the variables, they are as follows. My assumption based on your response is I should likely change the loop index variable to something besides the matrix k to avoid future confusion.
c = 50
z = [k 0 2 0; 0 k 0 2; 3 4 5 0; 4 3 0 5]

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

採用された回答

Scott MacKenzie
Scott MacKenzie 2021 年 6 月 22 日
編集済み: Scott MacKenzie 2021 年 6 月 22 日
I think this is what you are looking for. It updates k in the z matrix in each iteration of the loop. The max values accumulate in the vector x.
c = 50;
k = 0;
z = [k 0 2 0; 0 k 0 2; 3 4 5 0; 4 3 0 5];
x = [];
for k = 0:c
e = eig(z);
M = max(e);
x = [x,M];
% update k in z
z(1,1)=k;
z(2,2)=k;
end
x % output max values
  1 件のコメント
Nolan Ames
Nolan Ames 2021 年 6 月 22 日
That worked perfectly. Thank you for the timely response, I really appreciate it.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by