using multiple else if
74 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 14 Jul 2022
Edited: Stephen23
on 14 Jul 2022
"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.
Answers (1)
Jonas
on 14 Jul 2022
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
2 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!