How to simplify code into a for loop?

5 views (last 30 days)
Kostas Kalabokas
Kostas Kalabokas on 23 Feb 2022
Edited: Jan on 23 Feb 2022
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!

Accepted Answer

Jan
Jan on 23 Feb 2022
Edited: Jan on 23 Feb 2022
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.

More Answers (0)

Categories

Find more on Physics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!