Matrix

34
Matrix.java Below is the syntax highlighted version of Matrix.java from §9.5 Numerical Linear Algebra. /************************************************************************* * Compilation: javac Matrix.java * Execution: java Matrix * * A bare-bones immutable data type for M-by-N matrices. * *************************************************************************/ final public class Matrix { private final int M; // number of rows private final int N; // number of columns private final double[][] data; // M-by-N array // create M-by-N matrix of 0's public Matrix(int M, int N) { this.M = M; this.N = N; data = new double[M][N]; } // create matrix based on 2d array public Matrix(double[][] data) { M = data.length; N = data[0].length; this.data = new double[M][N]; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) this.data[i][j] = data[i][j]; } // copy constructor private Matrix(Matrix A) { this(A.data); } // create and return a random M-by-N matrix with values between 0 and 1 public static Matrix random(int M, int N) { Matrix A = new Matrix(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) A.data[i][j] = Math.random(); return A; } // create and return the N-by-N identity matrix public static Matrix identity(int N) { Matrix I = new Matrix(N, N); for (int i = 0; i < N; i++) I.data[i][i] = 1; return I; } // swap rows i and j

Transcript of Matrix

Page 1: Matrix

Matrix.java

Below is the syntax highlighted version of Matrix.java from §9.5 Numerical Linear Algebra.

/*************************************************************************

* Compilation: javac Matrix.java

* Execution: java Matrix

*

* A bare-bones immutable data type for M-by-N matrices.

*

*************************************************************************/

final public class Matrix {

private final int M; // number of rows

private final int N; // number of columns

private final double[][] data; // M-by-N array

// create M-by-N matrix of 0's

public Matrix(int M, int N) {

this.M = M;

this.N = N;

data = new double[M][N];

}

// create matrix based on 2d array

public Matrix(double[][] data) {

M = data.length;

N = data[0].length;

this.data = new double[M][N];

for (int i = 0; i < M; i++)

for (int j = 0; j < N; j++)

this.data[i][j] = data[i][j];

}

// copy constructor

private Matrix(Matrix A) { this(A.data); }

// create and return a random M-by-N matrix with values between 0 and 1

public static Matrix random(int M, int N) {

Matrix A = new Matrix(M, N);

for (int i = 0; i < M; i++)

for (int j = 0; j < N; j++)

A.data[i][j] = Math.random();

return A;

}

// create and return the N-by-N identity matrix

public static Matrix identity(int N) {

Matrix I = new Matrix(N, N);

for (int i = 0; i < N; i++)

I.data[i][i] = 1;

return I;

}

// swap rows i and j

Page 2: Matrix

private void swap(int i, int j) {

double[] temp = data[i];

data[i] = data[j];

data[j] = temp;

}

// create and return the transpose of the invoking matrix

public Matrix transpose() {

Matrix A = new Matrix(N, M);

for (int i = 0; i < M; i++)

for (int j = 0; j < N; j++)

A.data[j][i] = this.data[i][j];

return A;

}

// return C = A + B

public Matrix plus(Matrix B) {

Matrix A = this;

if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal

matrix dimensions.");

Matrix C = new Matrix(M, N);

for (int i = 0; i < M; i++)

for (int j = 0; j < N; j++)

C.data[i][j] = A.data[i][j] + B.data[i][j];

return C;

}

// return C = A - B

public Matrix minus(Matrix B) {

Matrix A = this;

if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal

matrix dimensions.");

Matrix C = new Matrix(M, N);

for (int i = 0; i < M; i++)

for (int j = 0; j < N; j++)

C.data[i][j] = A.data[i][j] - B.data[i][j];

return C;

}

// does A = B exactly?

public boolean eq(Matrix B) {

Matrix A = this;

if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal

matrix dimensions.");

for (int i = 0; i < M; i++)

for (int j = 0; j < N; j++)

if (A.data[i][j] != B.data[i][j]) return false;

return true;

}

// return C = A * B

public Matrix times(Matrix B) {

Matrix A = this;

if (A.N != B.M) throw new RuntimeException("Illegal matrix

dimensions.");

Matrix C = new Matrix(A.M, B.N);

Page 3: Matrix

for (int i = 0; i < C.M; i++)

for (int j = 0; j < C.N; j++)

for (int k = 0; k < A.N; k++)

C.data[i][j] += (A.data[i][k] * B.data[k][j]);

return C;

}

// return x = A^-1 b, assuming A is square and has full rank

public Matrix solve(Matrix rhs) {

if (M != N || rhs.M != N || rhs.N != 1)

throw new RuntimeException("Illegal matrix dimensions.");

// create copies of the data

Matrix A = new Matrix(this);

Matrix b = new Matrix(rhs);

// Gaussian elimination with partial pivoting

for (int i = 0; i < N; i++) {

// find pivot row and swap

int max = i;

for (int j = i + 1; j < N; j++)

if (Math.abs(A.data[j][i]) > Math.abs(A.data[max][i]))

max = j;

A.swap(i, max);

b.swap(i, max);

// singular

if (A.data[i][i] == 0.0) throw new RuntimeException("Matrix is

singular.");

// pivot within b

for (int j = i + 1; j < N; j++)

b.data[j][0] -= b.data[i][0] * A.data[j][i] / A.data[i][i];

// pivot within A

for (int j = i + 1; j < N; j++) {

double m = A.data[j][i] / A.data[i][i];

for (int k = i+1; k < N; k++) {

A.data[j][k] -= A.data[i][k] * m;

}

A.data[j][i] = 0.0;

}

}

// back substitution

Matrix x = new Matrix(N, 1);

for (int j = N - 1; j >= 0; j--) {

double t = 0.0;

for (int k = j + 1; k < N; k++)

t += A.data[j][k] * x.data[k][0];

x.data[j][0] = (b.data[j][0] - t) / A.data[j][j];

}

return x;

}

Page 4: Matrix

// print matrix to standard output

public void show() {

for (int i = 0; i < M; i++) {

for (int j = 0; j < N; j++)

System.out.printf("%9.4f ", data[i][j]);

System.out.println();

}

}

// test client

public static void main(String[] args) {

double[][] d = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 1, 3} };

Matrix D = new Matrix(d);

D.show();

System.out.println();

Matrix A = Matrix.random(5, 5);

A.show();

System.out.println();

A.swap(1, 2);

A.show();

System.out.println();

Matrix B = A.transpose();

B.show();

System.out.println();

Matrix C = Matrix.identity(5);

C.show();

System.out.println();

A.plus(B).show();

System.out.println();

B.times(A).show();

System.out.println();

// shouldn't be equal since AB != BA in general

System.out.println(A.times(B).eq(B.times(A)));

System.out.println();

Matrix b = Matrix.random(5, 1);

b.show();

System.out.println();

Matrix x = A.solve(b);

x.show();

System.out.println();

A.times(x).show();

}

}

Page 5: Matrix

Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne.

Last updated: Wed Feb 9 09:20:16 EST 2011.

Coding Array Matrix pada Java..

import javax.swing.JOptionPane;

public class array{

public static void main(String [] args){

System.out.println("=========================================");

System.out.println("=========== *ARRAY PADA JAVA* ===========");

System.out.println("============aliefendy.blogspot.com=============");

System.out.println("=========================================");

int bM1 = Integer.parseInt(JOptionPane.showInputDialog("Jumlah baris matrik 1?"));

int kM1 = Integer.parseInt(JOptionPane.showInputDialog("Jumlah kolom matrik 1?"));

int bM2 = Integer.parseInt(JOptionPane.showInputDialog("Jumlah baris matrik 2?"));

int kM2 = Integer.parseInt(JOptionPane.showInputDialog("Jumlah kolom matrik 2?"));

int matrix1[][] = new int[bM1][kM1];

int matrix2[][] = new int[bM2][kM2];

int matrix3[][] = new int[bM2][kM2];

int matrix4[][] = new int[bM2][kM2];

int matrix5[][] = new int[bM2][kM2];

for (int i = 0; i < bM1; i++) {

for (int j = 0; j < kM1; j++)

matrix1[i][j]=Integer.parseInt(JOptionPane.showInputDialog("[Matrix1]Baris ke-"+i+"

Kolom ke-"+j+" ?"));

}

for (int i = 0; i < bM2; i++) {

for (int j = 0; j < kM2; j++)

matrix2[i][j]=Integer.parseInt(JOptionPane.showInputDialog("[Matrix2] Baris ke-

"+i+" Kolom ke-"+j+" ?"));

}

for (int i = 0; i < bM1; i++) {

for (int j = 0; j < kM2; j++){

matrix3[i][j]= matrix1[i][j] + matrix2[i][j];

}

}

Page 6: Matrix

for (int i = 0; i < bM1; i++) {

for (int j = 0; j < kM2; j++){

matrix4[i][j]= matrix1[i][j] - matrix2[i][j];

}

}

for (int i = 0; i < bM1; i++) {

for (int j = 0; j < kM2; j++){

matrix5[i][j]= matrix1[i][j] * matrix2[i][j];

}

}

System.out.println("Matrik 1");

for (int i = 0; i < bM1; i++) {

for (int j = 0; j < kM2; j++)

System.out.print(" "+matrix1[i][j]);

System.out.println();

}

System.out.println("Matrik 2");

for (int i = 0; i < bM1; i++) {

for (int j = 0; j < kM2; j++)

System.out.print(" "+matrix2[i][j]);

System.out.println();

}

System.out.println("Hasil Jumlah :");

for (int i = 0; i < bM2; i++) {

for (int j = 0; j < kM2; j++)

System.out.print(" "+matrix3[i][j]);

System.out.println();

}

System.out.println("Hasil Kurang :");

for (int i = 0; i < bM2; i++) {

for (int j = 0; j < kM2; j++)

System.out.print(" "+matrix4[i][j]);

System.out.println();

}

System.out.println("HasiL Kali :");

for (int i = 0; i < bM2; i++) {

for (int j = 0; j < kM2; j++)

System.out.print(" "+matrix5[i][j]);

System.out.println();

} } }

9. 4. 1. Initialize a two-dimensional array in matrix

Page 7: Matrix

public class MainClass {

public static void main(String args[]) {

double m[][] = {

{ 0*0, 1*0, 2*0, 3*0 },

{ 0*1, 1*1, 2*1, 3*1 },

{ 0*2, 1*2, 2*2, 3*2 },

{ 0*3, 1*3, 2*3, 3*3 }

};

int i, j;

for(i=0; i<4; i++) {

for(j=0; j<4; j++)

System.out.print(m[i][j] + " ");

System.out.println();

}

}

}

(output):

0.0 0.0 0.0 0.0

0.0 1.0 2.0 3.0

0.0 2.0 4.0 6.0

0.0 3.0 6.0 9.0

Pengolahan Array dalam Java (array processing in java) Posted by xaxioza pada 04/04/2011 Array adalah suatu konsep penyimpanan data yang mana dapat menampung data dengan type

yang sama dalam elemen/ index jumlah yang banyak. Array dapat diimplementasikan kedalam

banyak kasus problematika. Misal, untuk menyelesaikan suatu Sistem persamaan Linear

dibutuhkan matrix yang merupakan representasi dari array 2 dimensi. Array multidimensi , juga

dibutuhkan untuk merepresentasikan koordinat benda 3 dimensi dalam bidang cartesius.

Operasi array ada 2 yaitu, operasi store/ simpan dan retrieve/ pengambilan data.

Contoh operasi store :

array[3]=5 Berarti nilai 5 dimasukkan ke dalam variable elemen ke – 3 dalam variable array

Contoh operasi retrieve :

int x=array[3] Berarti, variable x mengambil data dari variable array elemen ke – 3

Cara mendeklarasikan array dalam java adalah sbb :

Page 8: Matrix

tipedata [N] nama=new tipedata[N];

ex : int [10] arrayint=new int[10];

artinya variable arrayint merupakan array dalam bentuk integer dengan jumlah elemen 10

Contoh program matrix dalam java menggunakan konsep OOP

001 class awal{

002

003 protected int [][] mat1;

004

005 protected int [][] mat2;

006

007 protected int [][] matsum,matmulti,matmin;

008

009 protected int bar1,kol1,bar2,kol2;

010

011 public Scanner dataIn=new Scanner(System.in);

012

013 public void setBar1(int bar1){

014

015 this.bar1=bar1;

016

017 }

018

019 public int getBar1(){

020

021 return bar1;

022

023 }

024

025 public void setKol1(int kol1){

026

027 this.kol1=kol1;

028

029 }

030

031 public int getKol1(){

032

Page 9: Matrix

033 return kol1;

034

035 }

036

037 public void setBar2(int bar2){

038

039 this.bar2=bar2;

040

041 }

042

043 public int getbar2(){

044

045 return bar2;

046

047 }

048

049 public void setKol2(int kol2){

050

051 this.kol2=kol2;

052

053 }

054

055 public int getKol2(){

056

057 return kol2;

058

059 }

060

061 }

062

063 class konstruksi extends awal{

064

065 public konstruksi(int bar1,int kol1,int bar2, int kol2, int barhasil,int

kolhasil){

066

067 mat1=new int[bar1][kol1];

Page 10: Matrix

068

069 mat2=new int[bar2][kol2];

070

071 matsum=new int[barhasil][kolhasil];

072

073 matmin=new int[barhasil][kolhasil];

074

075 matmulti=new int[barhasil][kolhasil];

076

077 }

078

079 public void isiMatrix1(){

080

081 System.out.println("pengisian matrix ke 1");

082

083 for(int a=0;a<bar1;a++){

084

085 for(int b=0;b<kol1;b++){

086

087 System.out.print("masukkan isi Matrix 1

elemen ke["+a+1+","+b+1+"]=");mat1[a][b]=dataIn.nextInt();

088

089 }

090

091 }

092

093 }

094

095 public void cetakMatrix1(){

096

097 System.out.println("matrix ke 1");

098

099 for(int a=0;a<bar1;a++){

100

101 for(int b=0;b<kol1;b++){

102

Page 11: Matrix

103 System.out.print(mat1[a][b]+" ");

104

105 }

106

107 System.out.println();

108

109 }

110

111 }

112

113 public void isiMatrix2(){

114

115 System.out.println("pengisian matrix ke 2");

116

117 for(int a=0;a<bar1;a++){

118

119 for(int b=0;b<kol1;b++){

120

121 System.out.print("masukkan isi Matrix 1

elemen ke["+a+1+","+b+1+"]=");mat2[a][b]=dataIn.nextInt();

122

123 }

124

125 }

126

127 }

128

129 public void cetakMatrix2(){

130

131 System.out.println("matrix ke 2");

132

133 for(int a=0;a<bar1;a++){

134

135 for(int b=0;b<kol1;b++){

136

137 System.out.print(mat2[a][b]+" ");

Page 12: Matrix

138

139 }

140

141 System.out.println();

142

143 }

144

145 }

146

147 public void penjumlahan(){

148

149 if(bar1!=bar2){

150

151 System.out.println("ordo antar kedua matrix berbeda");

152

153 }

154

155 else{

156

157 for(int a=0;a<bar1;a++){

158

159 for(int b=0;b<kol1;b++){

160

161 matsum[a][b]=mat1[a][b]+mat2[a][b];

162

163 }

164

165 }

166

167 }

168

169 //cetak hasil jumlah

170

171 System.out.println("hasil penjumlahan ");

172

173 for(int a=0;a<bar1;a++){

Page 13: Matrix

174

175 for(int b=0;b<kol1;b++){

176

177 System.out.print(matsum[a][b]+" ");

178

179 }

180

181 System.out.println();

182

183 }

184

185 }

186

187 public void pengurangan(){

188

189 if(bar1!=bar2){

190

191 System.out.println("ordo antar kedua matrix berbeda");

192

193 }

194

195 else{

196

197 for(int a=0;a<bar1;a++){

198

199 for(int b=0;b<kol1;b++){

200

201 matsum[a][b]=mat1[a][b]+mat2[a][b];

202

203 }

204

205 }

206

207 }

208

209 //cetak hasil kurang

Page 14: Matrix

210

211 System.out.println("hasil pengurangan ");

212

213 for(int a=0;a<bar1;a++){

214

215 for(int b=0;b<kol1;b++){

216

217 System.out.print(matmin[a][b]+" ");

218

219 }

220

221 System.out.println();

222

223 }

224

225 }

226

227 public void perkalian(){

228

229 if(kol1!=bar2){

230

231 System.out.println("Jumlah kolom matrix ke-1 tidak sama dengan

jumlah baris matrix ke-2");

232

233 }

234

235 else{

236

237 for(int a=0;a<bar1;a++){

238

239 for(int b=0;b<kol2;b++){

240

241 for(int c=0;c<kol1;c++){

242

243 matmulti[a][b]=matmulti[a][b]+mat1[a][c]*mat2[c][b];

244

Page 15: Matrix

245 }

246

247 }

248

249 }

250

251 }

252

253 //cetak hasil kali

254

255 System.out.println("hasil perkalian ");

256

257 for(int a=0;a<bar1;a++){

258

259 for(int b=0;b<kol2;b++){

260

261 System.out.print(matmulti[a][b]+" ");

262

263 }

264

265 System.out.println();

266

267 }

268

269 }

270

271 }

272

273 class hasil{

274

275 public static void main(String [] args){

276

277 Scanner dataIn=new Scanner(System.in);

278

279 int bar1,kol1,bar2,kol2;

280

Page 16: Matrix

281 System.out.println("program operasi matrix menggunakan konsep OOP");

282

283 konstruksi matrix=new konstruksi(10,10,10,10,20,20);

284

285 System.out.print("masukkan jumlah baris matrix ke-1

= ");bar1=dataIn.nextInt();matrix.setBar1(bar1);

286

287 System.out.print("masukkan jumlah kolom matrix ke-1

= ");kol1=dataIn.nextInt();matrix.setKol1(kol1);

288

289 matrix.isiMatrix1();

290

291 System.out.print("masukkan jumlah baris matrix ke-2

= ");bar2=dataIn.nextInt();matrix.setBar2(bar2);

292

293 System.out.print("masukkan jumlah kolom matrix ke-2

= ");kol2=dataIn.nextInt();matrix.setKol2(kol2);

294

295 matrix.isiMatrix2();

296

297 matrix.cetakMatrix1();

298

299 matrix.cetakMatrix2();

300

301 matrix.penjumlahan();

302

303 matrix.pengurangan();

304

305 matrix.perkalian();

306

307 }

308

309 }

Page 17: Matrix

Matriks - Dua-dimensi array (Indo)

Sampai sekarang, semua array kami telah satu-dimensi array. Array ini memiliki "panjang",

tetapi "lebar" (atau tinggi) tetap sebagai hanya satu sel.

Kami sekarang siap untuk membahas dua-

dimensi array, yang disebut matriks (Tunggal:

matriks). Matriks A menyerupai tabel dengan

baris dan kolom.

Hal ini dimungkinkan untuk array untuk memiliki beberapa dimensi. Sebuah array tiga

dimensi, misalnya, memiliki 3 subscript, di mana masing-masing dimensi direpresentasikan

sebagai subscript dalam array. Meskipun dimungkinkan untuk array untuk memiliki

sejumlah dimensi, array sebagian besar dari satu atau dua dimensi.

Elemen-elemen dari matriks harus dari tipe data yang

sama.

Contoh: Computer Club berpartisipasi dalam serangkaian Pemrograman Memenuhi.

Tabel di bawah menunjukkan hasil Club, dimana skor maksimum untuk setiap kontestan

dalam memenuhi adalah 25.

Nama Temui # 1

Skor

Temui # 2

Skor

Temui # 3

Skor

Temui # 4

Skor

Temui # 5

Skor

1. Robbins 20 18 22 20 16

2. Montgomery 18 20 18 21 20

3. Stevenson 16 18 16 20 24

4. Norton 25 24 22 24 25

Catatan: Meskipun nama siswa dan nomor bertemu tidak ditampilkan, mereka bukan bagian dari data aktual

dan bukan merupakan bagian dari matriks. Ingat, data dalam array dua dimensi selalu dari tipe data yang sama.

Data yang ditampilkan dalam tabel ini terdiri dari 20 nilai - empat baris dengan lima kolom.

Matriks ini akan memiliki 20 sel, atau elemen.

Ketika anda mendefinisikan penyimpanan untuk matriks (array multi-dimensi), Anda harus

menentukan bahwa array memiliki lebih dari satu dimensi dengan menempatkan lebih dari

satu subskrip dalam tanda kurung setelah penunjukan tipe. Deklarasi berikut akan digunakan

untuk menyimpan data yang ditunjukkan pada tabel di atas:

Page 18: Matrix

int [] [] nilai = new int [4] [5]; / / Mendeklarasikan array 2-D

Deklarasi ini menciptakan sebuah matriks dengan unsur-unsur subscript berikut:

kolom

baris

[0] [0] [0] [1] [0] [2] [0] [3] [0] [4]

[1] [0] [1] [1] [1] [2] [1] [3] [1] [4]

[2] [0] [2] [1] [2] [2] [2] [3] [2] [4]

[3] [0] [3] [1] [3] [2] [3] [3] [3] [4]

Kode int [4] [5] menunjukkan bahwa akan ada empat array dari int dalam nilai array dengan

5 int di setiap array int.

Sementara kita memvisualisasikan pengaturan ini dengan memikirkan matriks baris dan

kolom, sesuatu yang sedikit berbeda terjadi dalam memori.

skor memegang referensi ke sebuah array dari 4 elemen di mana setiap elemen adalah referensi ke

array dari 5 integer.

Hal ini lebih mudah untuk hanya menganggapnya

sebagai sebuah grid atau matriks.

Pada kali, Anda mungkin perlu ingat bahwa setiap baris sebenarnya array. Ini "baris" array

dapat disebut sebagai nilai [0], nilai [1], nilai [2], dan nilai [3] di mana setiap baris adalah

tipe int [].

Bekerja dengan Matriks:

• Pengisian dengan daftar - Sama seperti bekerja dengan array satu dimensi, adalah

mungkin untuk mengisi array dua dimensi dengan menggunakan daftar pada saat array

dideklarasikan. Perhatikan "set" kawat gigi "dalam" daftar yang menunjukkan "array dari

Page 19: Matrix

array".

int [] [] = {{skor 20, 18, 22, 20, 16}, {18, 20, 18, 21, 20}, {16, 18, 16, 20, 24}, {25, 24, 22, 24, 25} };

Perhatikan tanda baca dalam daftar. The

"array" yang dipisahkan oleh koma, seperti

elemen biasa dalam daftar. Pastikan Anda

menyertakan awal dan akhir (semua

inklusif) kawat gigi.

• Tidak mengisi saat diumumkan - Ketika array dibuat secara otomatis diisi dengan

nol (untuk nilai-nilai numerik), palsu (untuk nilai boolean) atau null (untuk nilai-nilai

String).

• Mengisi dengan input pengguna - Ketika bekerja dengan dua-dimensi array (seperti

mengakses, percetakan mengisi, dll), perlu untuk menggunakan nested loop. Lingkaran luar

mengontrol jumlah baris dan loop batin mengontrol jumlah kolom.

/ / Mengisi matriks for (baris = 0; baris <4; baris + +) untuk (kolom = 0; kolom <5; kolom + +) { nilai [baris] [kolom] = Console.readInt ("Masukkan skor" + kolom + "untuk kontestan "+ baris); }

• Memanipulasi matriks - Misalkan Anda ingin menyimpan informasi untuk 30 siswa

dan 3 nilai ujian untuk setiap siswa masuk di keyboard. Selain itu, Anda ingin mencari rata-

rata (yang bisa menjadi nilai desimal) untuk setiap siswa, dan kemudian menyimpan rata-rata

ini dalam kolom keempat dari matriks yang sama. Ingat, Anda akan perlu untuk

mendapatkan nilai sebelum Anda dapat menghitung rata-rata. Berikut ini adalah satu

kemungkinan:

import java.io. *; BreezyGUI impor .*; masyarakat kelas matrixtest { public static void main (String [] args) { double [] [] nilai = new double [30] [4]; / / menciptakan ruang memori untuk matriks

seluruh / / Isi matriks dengan input pengguna dan menghitung rata-rata int baris, kolom; ganda jumlah, rata-rata; for (baris = 0; baris <3; baris + +)

Page 20: Matrix

{ sum = 0; untuk (kolom = 0; kolom <3; kolom + +) { nilai [baris] [kolom] = Console.readDouble ("Masukkan nilai" + (kolom +1) + "Untuk mahasiswa" + (baris 1)); jumlah = jumlah + nilai [baris] [kolom]; } rata = jumlah / 3; nilai [baris] [3] = rata-rata; } / / Mencetak hanya rata-rata System.out.println ("Kau menyelamatkan rata-rata sebagai berikut:"); for (baris = 0; baris <3; baris + +) { System.out.println ("Mahasiswa" + (baris + 1) + ":" + nilai [baris] [3]); } } }

• Panjang: Sama seperti perintah seperti list.length mengembalikan panjang array satu

dimensi, scores.length akan mengembalikan jumlah baris dalam array dua dimensi nilai [i] panjang akan mengembalikan jumlah kolom.. baris dengan subskrip i dalam array dua dimensi.

• Bekerja dengan Strings - Membuat matriks nilai String, mengisi matriks dengan

daftar, dan mencetak matriks. Perhatikan bahwa "internal" array ukuran berbeda. Perhatikan

bagaimana panjang. Digunakan untuk berurusan dengan berbagai panjang selama pencetakan. masyarakat kelas ArrayOfArraysAnimalDemo { public static void main (String [] args) { String [] [] binatang = { {"DanaDog", "WallyDog", "JessieDog", "AlexisDog", "LuckyDog"}, {"BibsCat", "DoodleCat", "MillieCat", "SimonCat"}, {"ElyFish", "CloieFish", "GoldieFish", "OscarFish", "ZippyFish", "TedFish"}, {"RascalMule", "GeorgeMule", "GracieMule", "MontyMule", "BuckMule", "RosieMule"} }; for (int i = 0; i <animals.length; i + +)

Page 21: Matrix

{ System.out.println (hewan [i] [0] + ":"); for (int j = 1; j <hewan [i] panjang;. j + +) { System.out.println (hewan [i] [j] + ""); } System.out.println (); } } }

Matrices - Two-dimensional arrays (Eng)

Up until now, all of our arrays have been one-dimensional arrays. These arrays have had

"length", but the "width" (or height) remained as only one cell.

We are now ready to discuss two-dimensional

arrays, called matrices (singular: matrix). A

matrix resembles a table with rows and

columns.

It is possible for arrays to have multiple dimensions. A three dimensional array, for

example, has 3 subscripts, where each dimension is represented as a subscript in the

array. While it is possible for arrays to have any number of dimensions, most arrays are of

one or two dimensions.

The elements of a matrix must be of the same data type.

Example: The Computer Club is participating in a series of Programming Meets. The

table below shows the Club's results, where the maximum score for each contestant in a

meet is 25.

Name Meet #1 Meet #2 Meet #3 Meet #4 Meet #5

Page 22: Matrix

Score Score Score Score Score

1. Robbins 20 18 22 20 16

2. Montgomery 18 20 18 21 20

3. Stevenson 16 18 16 20 24

4. Norton 25 24 22 24 25

Note: Although the students' names and the meet numbers are shown, they are not part of the actual data

and are not part of the matrix. Remember, the data in a two-dimensional array is always of the same data type.

The data displayed in this table consists of 20 values -- four rows by five columns. This

matrix will have 20 cells, or elements.

When you define storage for a matrix (a multi-dimensional array), you must specify that the

array has more than one dimension by putting more than one subscript in brackets after the

type designation. The following declaration would be used to store the data shown in the

table above:

int [ ] [ ] scores = new int [ 4 ] [ 5 ] ; // Declares a 2-D array

This declaration creates a matrix with the following subscripted elements:

columns

rows

[0][0] [0][1] [0][2] [0][3] [0][4]

[1][0] [1][1] [1][2] [1][3] [1][4]

[2][0] [2][1] [2][2] [2][3] [2][4]

[3][0] [3][1] [3][2] [3][3] [3][4]

The code int [ 4 ] [ 5 ] indicates that there will be four arrays of ints in the array scores, with 5

ints in each array of ints.

While we visualize this arrangement by thinking of a matrix of rows and columns, something

slightly different is occurring in the memory.

Page 23: Matrix

scores holds a reference to an array of 4 elements where each element is a reference to an array of 5

integers.

It is easier to simply think of it as a grid or matrix.

At times, you may need to remember that each row is actually an array. These "row" arrays can

be referred to as scores[0], scores[1], scores[2], and scores[3] where each row is type int [ ].

Working with Matrices:

• Filling by list - Just as working with a one-dimensional array, it is possible to fill a two

dimensional array by using a list at the time the array is declared. Notice the "sets" of braces

"within" the list denoting the "array of arrays".

int [ ] [ ] scores = { { 20, 18, 22, 20, 16 }, { 18, 20, 18, 21, 20 }, { 16, 18, 16, 20, 24 }, { 25, 24, 22, 24, 25 } };

Notice the punctuation in the list. The "arrays"

are separated by commas, as are ordinary

elements in a list. Be sure you include the

starting and ending (all inclusive) braces.

• No filling when declared - When an array is created it is automatically filled with a zero

(for numerical values), a false (for boolean values) or null (for String values).

• Filling with user input - When working with two-dimensional arrays (such as accessing,

filling, printing, etc.), it is necessary to use nested loops. The outer loop controls the number of

rows and the inner loop controls the number of columns.

// Filling the matrix for ( row = 0; row < 4; row ++ ) for ( column = 0; column < 5; column + + ) { scores [ row ] [ column ] = Console.readInt ("Enter score " + column + "for

Page 24: Matrix

contestant " + row ); }

• Manipulating a matrix - Suppose you want to save the information for 30 students and 3

exam grades for each student entered at the keyboard. In addition, you want to find the average

(which could be a decimal value) for each student, and then store this average in a fourth

column of the same matrix. Remember, you will need to obtain the grades before you can

compute the average. Here is one possibility:

import java.io.*; import BreezyGUI.*; public class matrixtest { public static void main(String[] args) { double [ ] [ ] grades = new double [ 30 ] [ 4 ] ; //create memory space for entire matrix // Fill the matrix with user input and compute average int row, column; double sum, average; for ( row = 0; row < 3; row ++ ) { sum = 0; for(column = 0; column < 3; column++) { grades[row][column] = Console.readDouble("Enter grade " + (column +1) + "for student " + (row+1)); sum = sum + grades[row][column]; } average = sum / 3; grades[row][3] = average; } // Print averages only System.out.println("You saved the following averages: "); for( row = 0; row < 3; row ++ ) { System.out.println("Student " + (row + 1) + ": " + grades[row][3]); } } }

• Length: Just as a command such as list.length returns the length of a one dimensional

array, scores.length will return the number of rows in this two-dimensional array. scores[ i

Page 25: Matrix

].length will return the number of columns of the row with subscript i in a two-dimensional array.

• Working with Strings - Create a matrix of String values, fill the matrix by list, and print

the matrix. Notice that the "internal" arrays are of differing sizes. Notice how the .length is used to deal with these varying lengths during printing. public class ArrayOfArraysAnimalDemo { public static void main(String[ ] args) { String[ ][ ] animals = { { "DanaDog", "WallyDog", "JessieDog", "AlexisDog", "LuckyDog" }, { "BibsCat", "DoodleCat", "MillieCat", "SimonCat" }, { "ElyFish", "CloieFish", "GoldieFish", "OscarFish", "ZippyFish", "TedFish"}, { "RascalMule", "GeorgeMule", "GracieMule", "MontyMule", "BuckMule", "RosieMule" } }; for (int i = 0; i < animals.length; i++) { System.out.print(animals[ i ] [ 0 ] + ": "); for (int j = 1; j < animals[ i ].length; j++) { System.out.print(animals[ i ][ j ] + " "); } System.out.println( ); } } }

Page 26: Matrix

Array - 2-dimensi (indo)

1 -, 2 -, dan lebih tinggi-dimensi array

Jawa, seperti kebanyakan bahasa, mendukung multi-dimensi array - 1-dimensi, 2-dimensi, 3-

dimensi, ... Dalam prakteknya kebanyakan array satu dimensi, dan dua-dimensi (baris dan

kolom) juga cukup umum. Array dimensi yang lebih tinggi kurang umum sehingga mereka tidak

digunakan dalam contoh, tapi tidak ada yang misterius tentang mereka dan prinsip-prinsip yang

sama berlaku.

Dua-dimensi array yang digunakan setiap kali data model yang terbaik diwakili dengan baris dan

kolom, atau memiliki dua aspek yang berbeda-beda (misalnya, jenis kelamin dan usia, berat dan

tinggi badan, ...). Itu juga ide tersebut, meskipun tidak pelaksanaan, grafis yang menentukan dua

(atau tiga) dimensi dengan posisi x dan y (dan z) mengkoordinasikan.

Terminologi. Hal lain Anda akan melihat array dua dimensi adalah matriks atau tabel.

Visualisasi array dua dimensi

2-dimensi array biasanya diwakili dengan gaya baris-kolom "spreadsheet". Asumsikan kita

memiliki sebuah array, a , dengan dua baris dan empat kolom.

int [] [] a = new int [2] [4]; / / Dua baris dan empat kolom.

a [0]

[0]

a [0]

[1]

a [0]

[2]

a [0]

[3]

a [1]

[0]

a [1]

[1]

a [1]

[2]

a [1]

[3]

Dua-dimensi array biasanya divisualisasikan sebagai sebuah matriks, dengan

baris dan kolom. Diagram ini menunjukkan array a dengan subskrip yang

sesuai.

Gaya: Gunakan konstanta nama untuk ukuran array

Ini berguna untuk mendefinisikan konstanta untuk jumlah baris dan kolom. Alasan bernama

konstanta yang lebih baik dapat kode adalah bahwa angka-angka ini mungkin merupakan bagian

dari domain masalah dan mereka akan digunakan di bagian lain dari kode. Jika perubahan adalah

setiap diperlukan (misalnya, jumlah tim di Sepuluh Besar), mengubah satu bernama konstan

akan mengubah semua bagian program. Setiap angka "konstan" hanya akan muncul sekali (yang

"KERING" prinsip).

static int akhir ROWS = 2;

static final int COLS = 3;

. . .

int [] [] board = new int [ROWS] [COLS];

Page 27: Matrix

Banyak baris dan indeks kolom (indeks adalah jamak tradisional Inggris, tapi banyak lebih

memilih indeks yang lebih modern) memiliki arti, dan tidak hanya cukup nomor sewenang-

wenang. Contoh berikut dapat digunakan untuk mewakili angka kecelakaan pada siang hari

bulan dan jam dari hari. Lihat masalah pemrograman di bawah ini untuk beberapa contoh

menggunakan array ini.

static int HARI akhir = 31;

static int JAM akhir = 24;

. . .

int [] [] kecelakaan = new int [HARI] [JAM];

Nilai awal

Anda dapat menetapkan nilai awal untuk array dengan cara yang sangat mirip dengan array satu

dimensi, tetapi dengan tingkat ekstra kawat gigi. Ukuran dimensi yang dihitung oleh kompilator

dari jumlah nilai. Hal ini akan mengalokasikan sebuah papan 3x3

int [] [] board = new int [] [] {{1,0,0}, {0,1,0}, {1,2,1}};

Gunakan bersarang untuk loop untuk memproses 2-dimensi array

Indeks nama Dua-dimensi array. Hampir selalu diproses dengan bersarang untuk loop. Dua

variabel indeks sering disebut i dan j (untuk baris dan kolom), tetapi lebih baik untuk

menggunakan baris dan col atau r dan c. Namun, jika baris dan kolom memiliki makna, seperti

bulan dan tahun, menggunakan nama-nama bukan nama netral makna.

Iterasi baris bawah, lalu menyeberangi kolom sering lebih baik. Praktek yang paling umum

adalah untuk loop luar akan untuk baris dan loop batin untuk kolom. Jika program Anda

membutuhkan iterasi luar dengan kolom, itu bagus, tapi default baris pertama iterasi memberikan

kinerja terbaik karena "locality of reference" meningkatkan Perfomance cache dan memori

virtual. Hal ini juga memungkinkan penggunaan foreach loop berguna.

1

2

3

4

5

6

7

8

9

/ / Tujuan: Tampilkan penggunaan nested loop untuk menampilkan 2D array.

/ / Pengarang: Fred Swartz, Feb 2008, Ditempatkan di domain publik.

/ / Menampilkan: * Dinamakan konstanta untuk dimensi.

/ / * Bersarang untuk loop untuk melintasi seluruh array 2D oleh baris.

/ / * Membangun output dalam String (StringBuilder lebih efisien).

impor javax.swing.JOptionPane;

public class TwoDimTest {

//... Tentukan konstanta bernama untuk sentralisasi definisi

/ / Dan mencegah penggunaan "angka ajaib".

static int akhir ROWS = 2;

static final int COLS = 4;

public static void main (String [] args) {

int [] [] a2 = new int [ROWS] [COLS];

Output string = ""; / / Akumulasi teks di sini (harus

Page 28: Matrix

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

StringBuilder).

//... Cetak array dalam bentuk persegi panjang menggunakan

bersarang untuk loop.

for (int baris = 0; baris <ROWS; baris + +) {

for (int col = 0; col <COLS; col + +) {

Output + = "" + a2 [baris] [col];

}

Output + = "\ n";

}

System.out.println (null, output);

}

}

Array dari array

Java membangun multi-dimensi array dari banyak array satu dimensi, yang disebut "array dari

array" pendekatan.

Ada beberapa konsekuensi menarik dari ini: Baris mungkin ukuran yang berbeda. Juga, setiap

baris adalah obyek (array) yang dapat digunakan secara independen.

Multi-dimensi array dibangun dari beberapa array satu dimensi

Seperti dengan semua array, yang new kata kunci harus digunakan untuk mengalokasikan memori untuk array. Sebagai contoh,

int [] [] a = new int [2] [4];

Page 29: Matrix

Ini array dua dimensi akan memiliki dua baris dan empat kolom.

Ini benar-benar mengalokasikan 3 benda: array satu-dimensi dari 2 elemen untuk menyimpan

setiap baris dari array yang sebenarnya, dan dua satu dimensi array dari 4 elemen untuk mewakili

isi dari baris.

+-----+ +-----+-----

+-----+-----+

| A [0] | -> | [0] |

[1] | [2] | [3] |

| | +-----+-----+---

--+-----+

+-----+

| | +-----+-----+---

--+-----+

| A [1] | -> | [0] |

[1] | [2] | [3] |

+-----+ +-----+-----

+-----+-----+

Di Jawa dua-dimensi array diimplementasikan adalah array satu

dimensi dari array satu dimensi - seperti ini.

Menggunakan panjang bukan. Konstanta bernama

Dinamakan konstanta membuat program sangat mudah dibaca, tetapi mereka mungkin tidak

tersedia jika array telah berlalu sebagai parameter. Anda bisa mendapatkan ukuran masing-

masing dimensi dengan .length atribut. Ini adalah gaya yang paling umum.

1

2

3

4

5

6

for (int baris = 0; baris <a2.length; baris + +) {

for (int col = 0;. col <a2 [baris] panjang; col + +) {

Output + = "" + a2 [baris] [col];

}

Output + = "\ n";

}

Menggunakan foreach lingkaran

Jika Anda akan di setiap baris seperti dalam contoh di atas, loop foreach menyediakan kode

sederhana. Untuk memahami ini Anda harus memahami alam array array dari array

multidimensi. Namun, foreach tidak dapat digunakan ketika pengindeksan selain maju dengan

langkah-langkah tunggal, dan hanya berlaku untuk membaca elemen dari array, tidak menulis

mereka.

1

2

3

4

5

6

untuk (int [] row: a2) {

for (int val: baris) {

Output + = "" + val;

}

Output + = "\ n";

}

Page 30: Matrix

Pemrograman masalah

1. Untuk accidents Array di atas menulis kode yang melakukan berikut ini: a. Menampilkan jumlah total kecelakaan? Petunjuk: Gunakan loop bersarang untuk

menambahkan semua elemen. b. Jam berapa lakukan kecelakaan paling banyak terjadi? Petunjuk: Gunakan pada loop

luar selama berjam-jam, di mana loop batin turun kolom dan menambahkan semua kecelakaan selama satu jam itu. Jauhkan maks seperti yang Anda lakukan untuk array satu dimensi.

c. Bagaimana Anda mendeklarasikan array tiga dimensi yang memiliki dimensi tambahan untuk 12 bulan?

Arrays - 2-dimensional (Eng)

1-, 2-, and higher-dimensional arrays

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional,

3-dimensional, ... In practice most arrays are one-dimensional, and two-dimensional (rows and

columns) are also quite common. Higher dimensional arrays are less common so they aren't used

in the examples, but there's nothing mysterious about them and the same principles apply.

Two-dimensional arrays are used whenever the model data is best represented with rows and

columns, or has two varying aspects (eg, gender and age, weight and height, ...). It's also the

idea, altho not the implementation, of graphics that specifies a two (or three) dimensional

position with an x and y (and z) coordinate.

Terminology. Other terms you will see for a two-dimensional array are matrix or table.

Visualizing two-dimensional arrays

2-dimensional arrays are usually represented with a row-column "spreadsheet" style. Assume we

have an array, a, with two rows and four columns.

int[][] a = new int[2][4]; // Two rows and four columns.

a[0][0] a[0][1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

Two-dimensional arrays are usually visualized as a matrix, with rows

and columns. This diagram shows the array a with its corresponding

subscripts.

Page 31: Matrix

Style: Use named constants for array sizes

It's useful to define constants for the number of rows and columns. The reason named constants

can better code is that these numbers may represent part of the problem domain and they will be

used in other parts of the code. If a change is every necessary (eg, the number of teams in the Big

Ten), changing one named constant will change all parts of the program. Each numeric

"constant" should only appear once (the "DRY" principle).

static final int ROWS = 2;

static final int COLS = 3;

. . .

int[][] board = new int[ROWS][COLS];

Many row and column indexes (indices is the traditional English plural, but many prefer the

more modern indexes) have a meaning, and aren't just simply arbitrary numbers. The following

example might be used to represent the number of accidents on by day of the month and the hour

of the day. See programming problems below for some examples using this array.

static final int DAYS = 31;

static final int HOURS = 24;

. . .

int[][] accidents = new int[DAYS][HOURS];

Initial values

You can assign initial values to an array in a manner very similar to one-dimensional arrays, but

with an extra level of braces. The dimension sizes are computed by the compiler from the

number of values. This would allocate a 3x3 board

int[][] board = new int[][] {{1,0,0},{0,1,0},{1,2,1}};

Use nested for loops to process 2-dimensional arrays

Index names. Two-dimensional arrays are almost always processed with nested for loops. The

two index variables are often called i and j (for the row and column), but it is better to use row

and col or r and c. However, if the row and column have meanings, like month and year, use

those names rather than a meaning neutral name.

Iterating down rows, then across columns is often better. The most common practice is for

the outer loop be for the row and the inner loop for the column. If your program requires the

outer iteration by columns, that's fine, but the default row-first iteration gives the best

performance because "locality of reference" improves the perfomance of cache and virtual

memory. It also allows use of the handy foreach loop.

1

2

// Purpose: Show use of nested loops to display 2D array.

// Author : Fred Swartz, Feb 2008, Placed in public domain.

// Shows : * Named constants for dimensions.

// * Nested for loops to traverse entire 2D array by rows.

Page 32: Matrix

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

// * Building the output in a String (StringBuilder more

efficient).

import javax.swing.JOptionPane;

public class TwoDimTest {

//... Define named constants to centralize definitions

// and prevent use of "magic numbers".

static final int ROWS = 2;

static final int COLS = 4;

public static void main(String[] args) {

int[][] a2 = new int[ROWS][COLS];

String output = ""; // Accumulate text here (should be

StringBuilder).

//... Print array in rectangular form using nested for loops.

for (int row = 0; row < ROWS; row++) {

for (int col = 0; col < COLS; col++) {

output += " " + a2[row][col];

}

output += "\n";

}

JOptionPane.showMessageDialog(null, output);

}

}

Page 33: Matrix

Arrays of arrays

Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of

arrays" approach.

There are a couple of interesting consequences of this: Rows may be different sizes. Also, each

row is an object (an array) that can be used independently.

Multi-dimensional arrays are built from multiple one-dimensional arrays

As with all arrays, the new keyword must be used to allocate memory for an array. For example,

int[][] a = new int[2][4];

This two-dimensional array will have two rows and four columns.

This actually allocates 3 objects: a one-dimensional array of 2 elements to hold each of the actual

row arrays, and a two one-dimensional arrays of 4 elements to represent the contents of the rows.

+-----+ +-----+--

---+-----+-----+

|a[0] | -> | [0] |

[1] | [2] | [3] |

| | +-----+--

---+-----+-----+

+-----+

| | +-----+--

---+-----+-----+

|a[1] | -> | [0] |

[1] | [2] | [3] |

+-----+ +-----+--

---+-----+-----+

In Java two-dimensional arrays are implemented is a one-dimensional

array of one-dimensional arrays -- like this.

Using .length instead of named constants

Named constants make a program very readable, but they may not be available if the array has

been passed as a parameter. You can get the size of each dimension with the .length attribute. This is the most general style.

1

2

3

4

5

6

for (int row = 0; row < a2.length; row++) {

for (int col = 0; col < a2[row].length; col++) {

output += " " + a2[row][col];

}

output += "\n";

}

Page 34: Matrix

Using foreach loop

If you are going across each row as in the above examples, the foreach loop provides simpler

code. To understand this you must understand the array of arrays nature of multidimensional

arrays. However, the foreach can not be used when indexing other than forward by single steps,

and it only applies to reading the elements of the array, not writing them.

1

2

3

4

5

6

for (int[] row : a2) {

for (int val : row) {

output += " " + val;

}

output += "\n";

}

Programming problems

1. For the accidents array above write code that does the following: a. Display the total number of accidents? Hint: Use nested loops to add all elements. b. At what hour do the most accidents occur? Hint: Use on outer loop over hours, where

the inner loop goes down the column and adds all the accidents for that hour. Keep max as you would for a one-dimensional array.

c. How would you declare a three-dimensional array that had an additional dimension for the 12 months?