Shortening nested If statements

HI Friends,
I am trying to shorten this nested if statement, is there a way to make it more compact ?
GR = [3.78 2.06 1.58 1.21 0.82]
for i=1:x
ig(i) = 3.78;
N(i) = Vel_mps(i)*io*ig(i)*60/pi/Dt;
% Gear change with speed exceeding 2000 rpm
if N(i) > Nopt
ig(i) = 2.06;
N(i) = Vel_mps(i)*io*ig(i)*60/pi/Dt;
if N(i) > Nopt
ig(i) = 1.58;
N(i) = Vel_mps(i)*io*ig(i)*60/pi/Dt;
if N(i) > Nopt
ig(i) = 1.21;
N(i) = Vel_mps(i)*io*ig(i)*60/pi/Dt;
if N(i) > Nopt
ig(i) = 0.82;
N(i) = Vel_mps(i)*io*ig(i)*60/pi/Dt;
end
end
end
end
end

 Respuesta aceptada

Jeff Miller
Jeff Miller el 20 de Mzo. de 2018
Approximately:
GR = [3.78 2.06 1.58 1.21 0.82];
magic_constants = [3.78 2.06 1.58 1.21 0.82];
for i=1:x
j = 0;
Less = false;
while ~Less & (j<numel(magic_constants)
j = j + 1;
ig(i) = magic_constants(j);
N(i) = Vel_mps(i)*io*ig(i)*60/pi/Dt;
Less = N(i) <= Nopt;
end;
end;

4 comentarios

DIP
DIP el 21 de Mzo. de 2018
Thank you Jeff..what is magic_constants?
Jeff Miller
Jeff Miller el 21 de Mzo. de 2018
Just an arbitrary name for an array to store your different ig values, initialized at the top. I wasn't sure what to call them, since I'm not sure what they reflect.
DIP
DIP el 21 de Mzo. de 2018
Thank you Jeff.
Jan
Jan el 21 de Mzo. de 2018
Editada: Jan el 21 de Mzo. de 2018
This code can be written with a FOR loop also:
GR = [3.78 2.06 1.58 1.21 0.82];
n = numel(GR);
for i = 1:x
c = Vel_mps(i) * io * 60 / pi / Dt;
for j = 1:n
d = GR(j) * c;
if d > Nopt
N(i) = d;
ig(i) = GR(j);
break; % Break: for j
end
end
end
And with FIND:
GR = [3.78 2.06 1.58 1.21 0.82];
NoptX = Nopt / (io * 60 / pi / Dt);
for i = 1:x
d = Vel_mps(i) * GR;
j = find(d > NoptX, 1);
N(i) = d(j);
ig(i) = GR(j);
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre View and Analyze Simulation Results en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

DIP
el 20 de Mzo. de 2018

Editada:

Jan
el 21 de Mzo. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by