How to get the maximum value from the numbers in file names using ImageJ macro

Hi there, I have a bunch of ROI files in a folder. Their names are in the pattern of Posxx-xx. What I want to do is:

  1. Find the ROI files that contain Pos109 in the names;(e.g, Pos109-1, Pos109-3,Pos109-5)
  2. Extract the number after Pos109- (e.g, 1, 3, 5)
  3. Combine the extracted numbers
  4. Eventually I want to find the maximum value from the extracted numbers (e.g,5)

I have wrote a macro in ImageJ as shown in below, and got stuck in Array.concat of the extracted numbers. Could anyone help to check my script? Thanks a lot!

files=newArray(0); 
dir=getDirectory("Select the directory"); 
print("\\Clear");
setBatchMode(false);
list=getFileList(dir); 
for(i=0;i<list.length;i++){ 
if(startsWith(list[i],"Pos109")){ 
        files=Array.concat(files,list[i]); //combine qualifed files
        } 
} 

for(j=0;j<files.length;j++){ 
        numbers = newArray(0);
        numberArray = newArray(files.length);
        subStringArray = split(files[j], "-" );
if ( lengthOf( subStringArray[1] ) == 7 ) { digits = 1; } else { digits = 2; }
number = parseInt( substring( subStringArray[1], 0, digits ) );
number = toString(number);

numberArray[j]=toString(number);
numbers = Array.concat(numbers,numberArray);
Array.print(numberArray);
//Array.print(numbers);
}

Hi @imag,

I think the issue is likely that you have your two “newArray” commands within your second for loop so you are recreating these arrays every time you progress through the loop thus undoing anything you put in them in the last loop.

Does it work if you put them before the loop is initiated?

1 Like

Hi Imurphy

You are correct! Now it is working!! Thank you so much

1 Like