Why isn't this if statement nested in a for loop working?

1 回表示 (過去 30 日間)
Kelsey
Kelsey 2014 年 7 月 15 日
コメント済み: Chad Greene 2014 年 7 月 15 日
I am trying to use fuel consumption, velocity, and time data from a real-world drive cycle to calculate the fuel consumed during idle (vehicle speed = 0). IdleFuel represents the volume of fuel consumed during idle; so when vehicle speed =/= 0, IdleFuel should be zero. Here is some sample data and my code (I simplified my actual data, for brevity):
% Time (s)
time = [0 1 2 3 4 5];
% Fuel consumed (L)
Fuel_Consumed = [0.5 1 1.5 2 2.5 3];
% Vehicle speed (mph)
VSPD = [0 10 20 0 10 20];
IdleFuelIndex = find(VSPD == 0); %(find indexes where VSPD = 0)
IdleTime = time(IdleFuelIndex); %s (times when VSPD = 0)
IdleFuel=0;
for n = 1:length(time)
if n == IdleFuelIndex
IdleFuel(n) = Fuel_Consumed(n);
else IdleFuel(n) = 0;
end
end
When I run this, I just get that IdleFuel=0...why is this? I think Matlab is having trouble recognizing what to do if the vehicle speed returns to zero after being nonzero; when I tried altering the data such that only the first entry in the VSPD vector was zero, it seemed to work...but if it returns to zero (such as the fourth entry in the VSPD vector), it just returns IdleFuel as 0. How can I fix this??
Thank you for your time!

回答 (1 件)

Chad Greene
Chad Greene 2014 年 7 月 15 日
It doesn't work because n (a scalar) will never equal IdleFuelIndex (a vector).
  3 件のコメント
Kelsey
Kelsey 2014 年 7 月 15 日
Update...I tried this:
% Time (s)
time = [0 1 2 3 4 5];
% Fuel consumed (L)
Fuel_Consumed = [0.5 1 1.5 2 2.5 3];
% Vehicle speed (mph)
VSPD = [0 10 20 0 10 20];
IdleFuelIndex = find(VSPD == 0); %(find indexes where VSPD = 0)
NonIdleFuelIndex = find(VSPD ~= 0);
IdleTime = time(IdleFuelIndex); %s (times when VSPD = 0)
NonIdleTime = time(NonIdleFuelIndex); %s
IdleFuel=0;
NonIdle = ismember(time,NonIdleTime);
Idle = ismember(time,IdleTime);
for n = 1:length(time)
if Idle(n) = 0 %(if not idle)
IdleFuel(n+1) = 0;
elseif Idle(n) = 1 %(if idle)
IdleFuel(n+1) = Fuel_Consumed(n+1);
end
end
though I'm still getting errors...any ideas?
Chad Greene
Chad Greene 2014 年 7 月 15 日
You need a double equals in these lines:
if Idle(n) == 0 %(if not idle)
and
elseif Idle(n) == 1 %(if idle)

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

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by