How to simplify code into a for loop?

조회 수: 2 (최근 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 CenterFile Exchange에서 Physics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by