How to simplify code into a for loop?

1 回表示 (過去 30 日間)
Kostas Kalabokas
Kostas Kalabokas 2022 年 2 月 23 日
編集済み: Jan 2022 年 2 月 23 日
I am creating the transfer functions for the different stories of the model for a buidling. My code is quite heavy, and it is very tedious to keep adding lines of code when I want to model more floors.
Is there anyway I can implement this code into a for loop?
a1=phi(1,1);
a2=phi(2,1);
a3=phi(3,1);
a4=phi(4,1);
q1_f=a1./(M_diag(1,1)*s.^2+C_diag(1,1)*s+K_diag(1,1));
q2_f=a2./(M_diag(2,2)*s.^2+C_diag(2,2)*s+K_diag(2,2));
q3_f=a3./(M_diag(3,3)*s.^2+C_diag(3,3)*s+K_diag(3,3));
q4_f=a4./(M_diag(4,4)*s.^2+C_diag(4,4)*s+K_diag(4,4));
M_diag, C_diag, K_diag are 4x4 matrices that have been previously defined.
Thank you!

採用された回答

Jan
Jan 2022 年 2 月 23 日
編集済み: Jan 2022 年 2 月 23 日
M_diag = rand(4,4);
C_diag = rand(4,4);
K_diag = rand(4,4);
a = phi(1:4, 1);
q_f = a ./ (diag(M_diag) .* s .^ 2 + diag(C_diag) .* s + diag(K_diag));
There is no need for a loop. Simply avoid to hide indices in the names of variables, but use vectors instead.
Hiding indices in names is a typical pitfall for beginners.
  1 件のコメント
Kostas Kalabokas
Kostas Kalabokas 2022 年 2 月 23 日
Hi Jan,
That makes much more sense!
Thank you,
Kostas

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by