[Pascal] Source Code Perkalian Matriks dengan Pascal


Seorang teman meminta untuk dibuatkan source code perkalian dua matriks dengan pascal. Berikut hasil yang di dapat. (Mungkin masih agak kurang optimal.)

Program PerkalianMatriks;
Uses crt;
Var
	MatA, MatB, MatAns : array [1..100, 1..100] of longint;
	mA, nA, mB, nB : integer; //baris dan kolom
	i, j, k : integer; //indeks pengulangan
	
Begin
	write('Masukkan jumlah baris untuk matriks A = '); readln(mA);
	write('Masukkan jumlah kolom untuk matriks A = '); readln(nA);
	write('Masukkan jumlah baris untuk matriks B = '); readln(mB);
	write('Masukkan jumlah kolom untuk matriks B = '); readln(nB);
	writeln;
	
	if (nA = mB) then
	begin
		//Input data matriks A
		writeln('Input data matriks A');
		for i := 1 to mA do
			for j := 1 to nA do
			begin
				write('MatA [', i:2, ',', j:2, '] = '); readln(MatA[i,j]);
			end;
		writeln;
		
		//Input data matriks B
		writeln('Input data matriks B');
		for i := 1 to mB do
			for j := 1 to nB do
			begin
				write('MatB [', i:2, ',', j:2, '] = '); readln(MatB[i,j]);
			end;		
		writeln;
		
		//View data matriks A
		writeln('Matriks A =');
		for i := 1 to mA do
		begin
			for j := 1 to nA do
			begin
				write(MatA[i,j]:4);
			end;
			writeln;
		end;
		
		//View data matriks B
		writeln('Matriks B =');
		for i := 1 to mB do
		begin
			for j := 1 to nB do
			begin
				write(MatB[i,j]:4);
			end;
			writeln;
		end;
		writeln;
		write('Tekan [Enter] untuk memulai perhitungan...');
		readln;
		
		//Perkalian Matriks
		for i := 1 to mA do
		begin
			for j := 1 to nB do
			begin
				MatAns[i, j] := 0; //inisialisasi (pengosongan matriks jawaban)
				for k := 1 to nA do
				begin
					MatAns[i, j] := MatAns[i, j] + (MatA[i, k] * MatB[k, j]);
				end;
			end;
		end;
		
		//View data matriks answer
		writeln('Matriks Ans = MatA x MatB = ');
		for i := 1 to mA do
		begin
			for j := 1 to nB do
			begin
				write(MatAns[i,j]:4);
			end;
			writeln;
		end;
		readln;
	end else
	begin
		writeln('Perkalian matriks gagal: Kolom MatA harus sama dengan Baris MatB');
	end;
End.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s