Info

This question is closed. Reopen it to edit or answer.

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

1 view (last 30 days)
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 Comments
Leon
Leon on 7 Apr 2020
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 on 7 Apr 2020
"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.

Answers (1)

Ameer Hamza
Ameer Hamza on 7 Apr 2020
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.

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!