필터 지우기
필터 지우기

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