using multiple else if
조회 수: 79 (최근 30일)
이전 댓글 표시
hello i have this code
clc
clear all
close all
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 = 0;
mean_travel1 = mean_travel1 + mean(arrival(1:i,:));
elseif 100 < depart_time(i) < 200
mean_travel2 = 0 ;
mean_travel2 = mean_travel2 + mean(arrival(1:i,:));
elseif 200 < depart_time(i) < 300
mean_travel3 = 0 ;
mean_travel3 = mean_travel3 + mean(arrival(1:i,:));
elseif 300 < depart_time(i) < 400
mean_travel4 = 0 ;
mean_travel4 = mean_travel4 + mean(arrival(1:i,:));
elseif 400 < depart_time(i) < 500
mean_travel5 = 0 ;
mean_travel5 = mean_travel5 + mean(arrival(1:i,:));
else
mean_travel6 = 0 ;
mean_travel6 = mean_travel6 + mean(arrival(1:i,:));
end
end
and it didn't recognize mean_trravel3 and the other variables after that
why this happen
also my depart time is 91x1
댓글 수: 1
Stephen23
2022년 7월 14일
편집: Stephen23
2022년 7월 14일
"it didn't recognize mean_trravel3 and the other variables after that why this happen "
Answer: Bad data design.
After those IF/ELSEIFs you have no easy way to know which of those variables you have created or not, so you have no easy way to process them. Your bad data design painted you into a corner, where you will either need to add some flags or write some ugly slow meta-programming to know which variables you created. Either way, it will add complexity and slow down your code.
Solution: Do not force meta-data (e.g. pseudo-indices) into variable names. Use actual indexing.
If you had simply stored the data in arrays using indexing you would not have this problem: the array(s) that you preallocated before the loop would always exist after the loop, togerther with any data that you add to it/them. Using arrays and indexing is how MATLAB works best. You should use arrays and indexing.
답변 (1개)
Jonas
2022년 7월 14일
the reason the variables are not recognized is, that the depending on your if clause, another variable is created (the created variable name depends on the if clause).
E.g. in your first if clause only the variable mean_travel1 is created, but not the variables mean_travel2 to 6
what me irritates is, that the content of all your if clauses is the same, e.g.
mean_travel2 = 0 ;
mean_travel2 = mean_travel2 + mean(arrival(1:i,:));
equals
mean_travel2 = 0 ;
mean_travel2 = 0 + mean(arrival(1:i,:));
equals
mean_travel2 = mean(arrival(1:i,:));
all other if clauses behave the same
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!