How to simplify code into a for loop?

2 次查看(过去 30 天)
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Physics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by