Say I have a matrix,
1 0 1
0 2 0
3 2 1
Is there a built in method in Java that would output the number 3 (the maximum) along with its coordinates?
If not then I think MATLAB might have spoiled me, hehe.
Say I have a matrix,
1 0 1
0 2 0
3 2 1
Is there a built in method in Java that would output the number 3 (the maximum) along with its coordinates?
If not then I think MATLAB might have spoiled me, hehe.
It depends on the implementation of the "matrix". As far as my experience with Java goes (and a brief Google search), there is no "standard" matrix class so I assume you are either using a multi-dimensional array (int[][] matrix
) or some 3rd party library.
In the former case, Java does provide the means for finding the max of a Collection. I assume it could somehow be applied to a multi-dimensional array; however it involves converting the array to a collection which, as this SO post points out, is very inefficient if all you need is min/max. Instead, you should write the min/max function yourself. Either it will be trivial for you and require little effort or you will learn something from doing it.
If you are using a 3rd party library, such as JAMA, then it entirely depends on the implementation of that library and I recommend you consult its documentation or source.
Here is some code that will do the maximum.
public FunRun()
{
int[][] array = { { 1, 1, 2 }, { 1, 0, 3 }, { 0, 2, 1 } };
System.out.println(max(array, 3, 3));
}
Integer max(int[][] array, int rows, int cols)
{
Integer result = null;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
if (result == null || result < array[row][col])
{
result = array[row][col];
}
}
}
return result;
}