Question

I am trying to get a simple elseif statement into IDL and am having a heck of a time with it. The matlab code looks something like this.

a = 1
b = 0.5

diff = a-b
thres1 = 1
thres2 = -1

if diff < thres1 & diff > thres2  
  'case 1'
elseif diff > thres1 
  'case 2'
elseif diff < thres2
  'case 3'
end

But the IDL code is not so simple and I am having troubles getting the syntax right. the help states: Syntax IF expression THEN statement [ ELSE statement ] or IF expression THEN BEGIN statements ENDIF [ ELSE BEGIN statements ENDELSE ]

But doesnt give an example on how to use multiple expressions and elseif. I have tried many variations and cant seem to get it right.

Anyone have suggestions? Here are some things I've tried:

if (diff lt thres1) and (diff gt thres2) then begin
  print, 'case 1'
endif else begin
if (diff gt thres1) then
  print, 'case 2'
endif else begin
if (diff lt thres2) then
  print, 'case 3'
endif 

if (diff lt thres1) and (diff gt thres2) then begin
  print, 'case 1'
else (diff gt thres1) then
  print, 'case 2'
else (diff lt thres2) then
  print, 'case 3'
endif 
Was it helpful?

Solution

There is no elseif statement in IDL. Try:

a = 1
b = 0.5

diff = a - b
thres1 = 1
thres2 = -1

if (diff lt thres1 && diff gt thres2) then begin
  print, 'case 1'
endif else if (diff gt thres1) then begin
  print, 'case 2'
endif else if (diff lt thres2) then begin
  print, 'case 3'
endif

OTHER TIPS

So I figured it out. For those of us that are new to the IDL language.

It appears to me that IDL can only handle 2 cases for each if statement, so I had to write in another 'if' block.

hope this helps someone out there.

a = 1;
b = 2.5;

diff = a-b;
thres1 = 1;
thres2 = -1;

if diff gt thres1 then begin
  print,'case 1'
endif

if (diff lt thres2) then begin
  print,'case 2'
  endif else begin
  print,'case 3'
endelse 

mgalloy's answer is correct, but you might also see people (like me), who don't use begin/endif when there's only a single line. (of course, this leads to problems if someone goes back and tries to insert a line, not realizing what you did, so Michael's approach is probably better ... this is just so that when you see this formatting, you realize it's doing the same thing:

if (diff lt thres1 && diff gt thres2) then $
  print, 'case 1' $
else if (diff gt thres1) then $
  print, 'case 2' $
else if (diff lt thres2) then $
  print, 'case 3'

or a format that might make someone less prone to insertion:

if      (diff lt thres1 && diff gt thres2) then print, 'case 1' $
else if (diff gt thres1)                   then print, 'case 2' $
else if (diff lt thres2)                   then print, 'case 3'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top