Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How to write a loop so that I do not need to repeat my super long inner loop?

1 回表示 (過去 30 日間)
Leon
Leon 2020 年 4 月 7 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
The station number column of my data can be either numerical or string. I have to rely on the station number info to split the data into multiple stations.
Below is my code:
% start the loop to split the data into stations:
if isfloat(any(T1.(app.stationN.Value))) % numerical
Ind_station = T1.(app.expocodeN.Value);
Ind_STA = Ind_station(1)
for i=2:m+1;
if Ind_station(i) == Ind_STA;
% 20000 lines of code
end
end
else % string
Ind_station = T1.(app.expocodeN.Value);
Ind_STA = Ind_station{1}
for i=2:m+1;
if strcmp(Ind_station{i}, Ind_STA)
% 20000 lines of code
end
end
end
Here is the problem, I have over 20,000 lines of code within the inner loop. How do I write the outer loop so that I do not need to repeat the 20,000 lines of code in two places?
Thanks.
  3 件のコメント
Leon
Leon 2020 年 4 月 7 日
Thanks!
The thing is that I have so many variables to initialize, and so many variables to carry over, if there is another option, I'd want to stay away from creating functions.
Stephen23
Stephen23 2020 年 4 月 7 日
"The thing is that I have so many variables to initialize, and so many variables to carry over..."
It is often convenient to store many variables in one structure or table, which makes passing them to a function trivial.
"...I'd want to stay away from creating functions."
If you want to write efficient, repeatable, testable, debuggable code then I strongly recommend using functions.

回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 4 月 7 日
As mentioned by Stephen, the best strategy is to create a function. If there is an issue about carrying the variables, then you can create a struct or a cell array to make it easier to carry them. However, If you still want to make minimal changes to your code, then you can create a script with 2000 lines of code and run the script in your current code.
Create a script myCode.m:
% write the 2000 lines of code
and then in your current script
if isfloat(any(T1.(app.stationN.Value))) % numerical
Ind_station = T1.(app.expocodeN.Value);
Ind_STA = Ind_station(1)
for i=2:m+1;
if Ind_station(i) == Ind_STA;
run('myCode.m');
end
end
else % string
Ind_station = T1.(app.expocodeN.Value);
Ind_STA = Ind_station{1}
for i=2:m+1;
if strcmp(Ind_station{i}, Ind_STA)
run('myCode.m');
end
end
end
This is effectively equivalent to your current code.

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by