Java Reference
In-Depth Information
This index remapping
5
is quite cumbersome to use in practice and may
yield various insidious bugs. Fortunately in Java, we can also create
multi-
dimensional
arrays easily; Java will perform the necessary index remapping
accordingly. A regular bi-dimensional array consists of
n
lines, each line being
itselfanarrayof
m
elements. A 2D matrix of integers has type
int [] []
and
is declared, created and initialized as follows:
int[][]matrix;
matrix=new int[n][m];
By default at the initialization stage, the array
matrix
is filled up with all zero
elements. We can change the contents of this 2D array using two
nested
loops,
as follows:
for(int i=0; i<n; i++)
for(int j=0; j<m;j++)
matrix[i][j]=i*j+1;
These constructions extend to arbitrary array dimensions. For example, a 3D
array may be defined as follows:
int[][][]volume;
volume=new double[depth][height][width];
Let us illustrate the manipulations of linear and bi-dimensional arrays by imple-
menting the matrix vector product operation. Observe the declaration/creation
and initialization of a 2D array by enumerating all its elements:
int [][] M={{1, 2, 3}, {4,5,6}, {7,8,9}};
Program 4.11
Matrix-vector product function
class
MatrixVectorProduct
{
static int
[] MultiplyMatrixVector (
int
[][] mat,
int
[] v)
{
int
[] result;
result=
new i n t
[mat. length ];
for
(
int
i=0;i
<
result . length ; i++)
{
result [ i ]=0;
for
(
int
j=0;j
<
v. length ; j++)
result [ i]+= mat[ i ][ j ]
∗
v[ j ];
}
return
result ;
}
public static void
main( String [ ]
args )
{
int
[][] M=
{{
1, 2, 3
}
,
{
4,5,6
}
,
{
7,8,9
}}
;
int
[] v=
{
1,2,3
}
;
5
We arbitrarily chose row major order. We can also choose the column major order.
Search WWH ::
Custom Search