Re: macro creating n Arrays within a "for"-loop

Posted by Michael Schmid on
URL: http://imagej.273.s1.nabble.com/macro-creating-n-Arrays-within-a-for-loop-tp3688201p5016852.html

Hi Sylvia,

as I understand it, the idea for packing several arrays of different
length into one big array is something like the following:


// This macro creates a big array containing several smaller ones
macro 'SmallArrays in Big Array' {
   //Create the arrays and fill them
   nArray = 7;  //we have 7 small arrays
   bigArray = newArray(1000);     //ImageJ extends it if required
   offsets = newArray(nArray+1);  //small array beginnings in bigArray
   for (iArray=0; iArray<nArray; iArray++) {
     smallArraysize = 2+round(2*random); //whatever size we want
     for (i=0; i<smallArraysize; i++) {
       value = i*i; //whatever value we want to save
       putArrayElement(bigArray, offsets, iArray, i, value);
     }
   }

   //Read the arrays
   for (iArray=0; iArray<nArray; iArray++) {
     print("==== Array number ", iArray, "====");
     smallArraysize = getArrayLength(iArray);
     for (i=0; i<smallArraysize; i++) {
       value = getArrayElement(bigArray, offsets, iArray, i);
       print ("element ", i, ": ", value);
     }
   }
}

   // Writes the i-th value into array number 'iArray'
   // Works correctly only if the small arrays are filled
   // in increasing sequence (starting with all elements of
   // iArray = 0, then all elements of iArray = 1, etc.
   // Later modification of array elements are allowed
   // as long as the array sizes are not extended.
   function putArrayElement(bigArray, offsets, iArray, i, value) {
     if (iArray >= lengthOf(offsets)-1)
       exit("No small Array #"+iArray);
     index = offsets[iArray] + i;
     bigArray[index] = value;
     if (offsets[iArray+1] < index+1)
       offsets[iArray+1] = index+1;
   }

   // Reads the i-th value into array number 'iArray'
   function getArrayElement(bigArray, offsets, iArray, i) {
     if (iArray >= lengthOf(offsets)-1)
       exit("No small Array #"+iArray);
     if (i >= offsets[iArray+1] - offsets[iArray])
       exit("Small Array "+iArray+" has no #"+i);
     index = offsets[iArray] + i;
     return bigArray[index];
   }

   // Gives the length of the given array
   function getArrayLength(iArray) {
     return offsets[iArray+1] - offsets[iArray];
   }


Michael
________________________________________________________________
On 2016-07-08 23:45, Sylvia Neumann wrote:
> Hi Joachim,
>
> I am trying to do something similar and don't really understand what a
> variable offset is. Could you write an example of that solution? That would
> be a great help! Thank you.
>
> --
> View this message in context: http://imagej.1557.x6.nabble.com/macro-creating-n-Arrays-within-a-for-loop-tp3688201p5016835.html

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html