using multiple else if
74 次查看(过去 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!