How to continue to loops
조회 수: 1 (최근 30일)
이전 댓글 표시
HI
One thing that I want to do is after first if I want to continue to sum the values in arrival in period between 100 and 200 and and other periods but I don't know how to do that and how to define 'i 'where to start after first if . 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
댓글 수: 0
채택된 답변
Amritesh
2022년 7월 14일
편집: Amritesh
2022년 7월 14일
In for loop, index = startVal:endVal is the syntax. So, you can write
for i = 1:length(depart_time)
statements
end
Hope this resolves your doubt.
댓글 수: 5
Amritesh
2022년 7월 14일
If you are trying to store arrival time for each period and calculate mean afterwards. Then, first add that in a variable and count how many times that period occur and then divide that to get the result.
sum_travel1 = 0;
sum_travel2 = 0;
sum_travel3 = 0;
sum_travel4 = 0;
sum_travel5 = 0;
sum_travel6 = 0;
count_travel1 = 0;
count_travel2 = 0;
count_travel3 = 0;
count_travel4 = 0;
count_travel5 = 0;
count_travel6 = 0;
for i = 1:length(depart_time)
if depart_time(i) < 100
sum_travel1 = sum_travel1 + arrival(i);
count_travel1 = count_travel1 + 1;
elseif 100 < depart_time(i) & depart_time(i)< 200
sum_travel2 = sum_travel2 + arrival(i);
count_travel2 = count_travel2 + 1;
elseif 200 < depart_time(i) & depart_time(i) < 300
sum_travel3 = sum_travel3 + arrival(i);
count_travel3 = count_travel3 + 1;
elseif 300 < depart_time(i) & depart_time(i) < 400
sum_travel4 = sum_travel4 + arrival(i);
count_travel4 = count_travel4 + 1;
elseif 400 < depart_time(i) & depart_time(i) < 500
sum_travel5 = sum_travel5 + arrival(i);
count_travel5 = count_travel5 + 1;
else
sum_travel6 = sum_travel6 + arrival(i);
count_travel6 = count_travel6 + 1;
end
end
mean_travel1 = sum_travel1/count_travel1;
mean_travel2 = sum_travel1/count_travel2;
mean_travel3 = sum_travel1/count_travel3;
mean_travel4 = sum_travel1/count_travel4;
mean_travel5 = sum_travel1/count_travel5;
mean_travel6 = sum_travel1/count_travel6;
You can also create an array sum and count of length 6 and use them as variable instead of 12 variables.
Hope this solves your doubt.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!