How to build a function to make a working code more flexible?

1 回表示 (過去 30 日間)
Loren99
Loren99 2022 年 12 月 8 日
編集済み: Stephen23 2022 年 12 月 12 日
Hi everyone! I have this main script which works and that finds me the passages of a satellite at a certain longitude. In this code, I have 4 satellites. These satellites are found separated from each other by a quarter of longitude (it means that if the first satellite passes at longitude 0 and again at longitude -24°, I will have the passage of satellite 2 at -6°, the passage of satellite 3 at -12° and the passage of satellite 4 at -18°). Now I would like to make the code more flexible (maybe building a function), because in this case I have 4 satellites, but I could have only 2 satellites separated by half longitude (it means that if the first satellite passes at longitude 0 and again at longitude -24°, I will have the passage of satellite 2 at -12°) or I could have 5 satellites separated by longitude/5 (with the same logic). How can I do that? Here the code
clc
clear all
close all
R=245;
N=16;
Q=R/N;
PassNo_sat1=1:1:R;
PassNo_sat2=1:1:R;
PassNo_sat3=1:1:R;
PassNo_sat4=1:1:R;
deltaLam_sat1=-2*pi/Q;
deltaLam_sat2=deltaLam_sat1/4;
deltaLam_sat3=deltaLam_sat1/2;
deltaLam_sat4=3*deltaLam_sat1/4;
lam_sat1(1)=0; %0 deg
lam_sat2(1)=deltaLam_sat2; %-6 deg
lam_sat3(1)=deltaLam_sat3; %-12 deg
lam_sat4(1)=deltaLam_sat4; %-18 deg
lam_sat2(1)=deltaLam_sat2;
dummy_sat2(1)=exp(1i*lam_sat2(1));
lamMpi2pi_sat2(1)=angle(dummy_sat2(1));
new_lampi2pi_in_deg_sat2(1) = rad2deg(lamMpi2pi_sat2(1));
lam_sat3(1)=deltaLam_sat3;
dummy_sat3(1)=exp(1i*lam_sat3(1));
lamMpi2pi_sat3(1)=angle(dummy_sat3(1));
new_lampi2pi_in_deg_sat3(1) = rad2deg(lamMpi2pi_sat3(1));
lam_sat4(1)=deltaLam_sat4;
dummy_sat4(1)=exp(1i*lam_sat4(1));
lamMpi2pi_sat4(1)=angle(dummy_sat4(1));
new_lampi2pi_in_deg_sat4(1) = rad2deg(lamMpi2pi_sat4(1));
...and so on

採用された回答

Jon
Jon 2022 年 12 月 8 日
The first thing you should do to greatly simplify your code and make it more flexible is to avoid using variable names with numerical values and instead use arrays. So for example instead of your
lam_sat1(k),lam_sat2(k),lam_sat3(k), lam_sat4(k)
Use a two dimensional array and just define
lam_sat(j,k)
where j = 1,2,3,4
  1 件のコメント
Stephen23
Stephen23 2022 年 12 月 12 日
編集済み: Stephen23 2022 年 12 月 12 日
In addition to Jon's excellent advice, you should read this:

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by