Integer comparison in ImageJ macro

Hi all,

I am stuck at a point where I really should not be stuck. I am writing a macro that reads in a look up table to find the indices that correspond to a certain range of values in the LUT.

Here is the code snippet:

filestring=File.openAsString(path); 
lut=split(filestring, "\n"); 
 
s = 0; e = 0; start = 250; end = 3500;
for(i=0;i<px_x;i++){
    if(lut[i]>=start && s==0){
        s = i;
    }
    if(lut[i]>=end && e==0){
        e = i;
    }
}

(by the way, can I omit the {} in a one-line if-statement as I can in C?)

Now, interestingly, the second if-clause always triggers when lut[i] is larger than 350, not 3500 (aka way too early)
If i set end to 50000, it triggers at 500. If i set it to 3.5E3, at 350. Does anyone have an idea what causes this or what I am not getting?

Thanks a lot
Toby

Just try it! :wink: The answer is yes.

I cannot reproduce your issue. Did you check the current value of lut[i] inside the if statement? What’s the content of the lut array after being read from the file?

1 Like

Thanks a lot for your help. If I print out some of the values like this (I should have included those in the first post already, sorry)

for(i=0;i<px_x;i++) { 
    if(lut[i]>=start && s==0) { 
        print(lut[i]); s=i;
    } 
    if(lut[i]>=end && e==0) { 
        print(lut[i-1]); print(lut[i]); print(lut[i+1]); e=i; 
    }
}

i get:

250.055 (this is wanted behaviour, first if clause)
350.055
357.703 (<- second ifclause triggers here)
365.345

now I set ‘end’ to 5000:

250.055 (1st)
494.308
501.839 (2nd)
509.364

Same output for end=5e4.

I uploaded the LUT here. As far as I can tell, the values are being read correctly, it’s just the comparing that goes wrong.

You are comparing text values (Strings) instead of numbers here, i.e. 350.703 is “larger” than 3500 because the macro language is comparing the string values "350.703" and "3500". See this little macro for illustration:

if ("350.055" > 3500) // false
    print("1: true");
if ("357.703" > 3500) // true
    print("2: true");
if ("350.055" > "3500") // false
    print("3: true");
if ("357.703" > "3500") // true
    print("4: true");

To avoid that, you should use the parseFloat(string) macro function:

for(i=0;i<px_x;i++){
    if(parseFloat(lut[i])>=start && s==0){
        s = i;
    }
    if(parseFloat(lut[i])>=end && e==0){
        e = i;
    }
}

NB: When using one of the supported full-fledged scripting languages (other than the ImageJ 1.x macro language), this error would have been easier to spot because your script would error out with something like:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
2 Likes

Thanks a lot, that was indeed the case.
Also, thanks for the addendum. I wasn’t even aware of the supported scripting languages - that should make things a lot easier in the future.