public float[] addUp(float[][] yourArrays) {
if(yourArrays == null)
return null;
int i, j;
int arrayLength = 0;
float[] toReturn = null;
//get the length of the array that will be returned
for(i = 0; i < yourArrays.length; i++) {
if((yourArrays[i] != null) && yourArrays[i].length > arrayLength)
arrayLength = yourArrays[i].length;
}
//now build the array that will be returned, but only if there
//have been any values at all
if(arrayLength != 0) {
//create the array
toReturn = new float[arrayLength];
//fill it
for(i = 0; i < yourArrays.length; i++) {
for(j = 0; j < arrayLength; j++) {
if((yourArrays[i] != null)
&& (j < yourArrays[i].length)
toReturn[j] += yourArrays[i][j];
}
}
}
return toReturn;
}
This should do what you want; it selects only values from arrays that have been initialized, only up until the last element of each array (so you won't have an ArrayOutOfBoundsException) and only if there where any values at all.
Runtime is in O([length of the longest array] * [number of arrays]).
Return values are
null if none of the arrays were initialized or if the longest array that was initialized had a length of 0;
- a float[] holding in each cell the sum of all values for which any of your initial arrays had something set.
if (a[i] != null) {for (j=0; j<n; j++) {res[j] += a[i][j];}}