Home > Software engineering >  How to continue loops with few if statement between them
How to continue loops with few if statement between them

Time:07-14

One thing that I want to do is after first if I want to continue to sum arrival in period between 100 and 200 and so on but I don't know how to do that I want only to sum the values in that period first if is ok but I don't know how to continue

arrival=xlsread('tripinfo.xlsx','G:G');
depart_time=xlsread('tripinfo.xlsx','B:B');

for i = 1:1:91
    if depart_time(i) < 100

        mean_travel1 = sum(arrival(1:i,1));
    elseif 100 < depart_time(i) & depart_time(i)< 200
        mean_travel2 = sum(arrival(i,1));
    elseif 200 < depart_time(i) & depart_time(i) < 300
        mean_travel3 = sum(arrival(i,1));
    elseif 300 < depart_time(i) & depart_time(i) < 400
        mean_travel4 =  sum(arrival(i,1));
    elseif 400 < depart_time(i) & depart_time(i) < 500
        mean_travel5 =  sum(arrival(i,1));
        else 
        mean_travel6 =  sum(arrival(i,1));
        
    
    end
end

CodePudding user response:

If indexes in depart_time are the same to arrival, I guess that right because you are using a for-loop mixing both indexes i. You don't need to use for-loops or if statements. Just find the indexes you want for each condition using find function. A faster code will be summarising this one using logic indexing but it is more complicated to understand if you aren't experienced. Also, I suggest you add some >= or <= to any boundary in the intervals because if you have exactly 100 (for example) you will miss that value.

arrival=xlsread('tripinfo.xlsx','G:G');
depart_time=xlsread('tripinfo.xlsx','B:B');

% < 100
idx_100 = find(depart_time < 100); % indexes where time < 100
idx_100_200 = find(depart_time >= 100 & depart_time > 200) ; % between 100 and 200

% continue with the rest of statements

% Now, if you want the mean (you are calling your variable mean right? ) 
% you have to divide by the total number of values. If you just want the 
% cumulative sum remove the division part.

mean_travel1  = sum(arrival(idx_100,1))/length(idx_100); 
mean_travel2 = sum(arrival(idx_100_200,1))/length(idx_100_200);
% Continue with the rest
  • Related