using multiple else if

1 ビュー (過去 30 日間)
arash rad
arash rad 2022 年 7 月 14 日
編集済み: Stephen23 2022 年 7 月 14 日
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
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
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
  2 件のコメント
arash rad
arash rad 2022 年 7 月 14 日
I understand The answer
I should write statement in if clause like this
elseif 200 < depart_time(i) & depart_time(i) < 300

サインインしてコメントする。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by