- Put the code into a function.
- Call the function.
Info
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
How to write a loop so that I do not need to repeat my super long inner loop?
    4 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
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 comentarios
  Stephen23
      
      
 el 7 de Abr. de 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.
Respuestas (1)
  Ameer Hamza
      
      
 el 7 de Abr. de 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.
0 comentarios
La pregunta está cerrada.
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


