【IDL】多条件判断的另类写法(case代替i)
对数组X,函数Y与之对应关系如下:
- 如果X小于0.1那么函数就是 y=9.3x+0.072
- 如果x大于0.1小于0.35那么函数就是y=0.16
- 如果X大于0.35小于1.75那么函数就是y=0.0504/x
- 如果x大于1.75小于20那么函数就是y=0.88-0.0035x
- 其他情况y=x
那么如果用IDL程序实现可以用IF THEN ELSE来写,如下:
x=FINDGEN(2000)*(0.01)
y = x
FOR i=0,N_ELEMENTS(x)-1 DO BEGIN
IF x[i] LT 0.1 THEN BEGIN
y[i] = 9.3*x[i]+0.072
ENDIF ELSE IF x[i] LT 0.35 THEN BEGIN
y[i] = 0.16
ENDIF ELSE IF x[i] LT 1.75 THEN BEGIN
y[i] =0.0504/x[i]
ENDIF ELSE IF x[i] LT 20 THEN y[i] = 0.88-0.0035*x[i]
ENDFOR
当然,为了省事好看,可以用case来实现,简单明了:
x=FINDGEN(2000)*(0.01)
y = x
FOR i=0,N_ELEMENTS(x)-1 DO BEGIN
CASE 1 OF
x[i] LT 0.1: y[i] = 9.3*x[i]+0.072
(x[i] GE 0.1) AND (x[i] LT 0.35): y[i] = 0.16
(x[i] GE 0.35) AND (x[i] LT 1.75): y[i] =0.0504/x[i]
(x[i] GE 1.75) AND (x[i] LT 20): y[i] = 0.88-0.0035*x[i]
ELSE:
ENDCASE
ENDFOR