MIPS 2x2 Matrix Multiplication Code Logical Error

78 Views Asked by At

I am having trouble writing code for a matrix multiplication program in MIPS programming language. The code is meant to multiply two 2x2 matrices and output a result matrix. It has user input and an output in the console as text.

I have tested the code in qtSpim and it has no syntax errors. The error in the code is in the logic of it all and it does not perform as intended.

.data
prompt1: .asciiz "Enter the elements of matrix A (2x2): "
prompt2: .asciiz "Enter the elements of matrix B (2x2): "
result_str: .asciiz "Result matrix (2x2) is: \n"
.text
.globl main
main:
li $v0, 4
la $a0, prompt1
syscall
jal read_matrix
la $t0, matrix_a
sw $v0, ($t0)
sw $v1, 4($t0)
sw $a0, 8($t0)
sw $a1, 12($t0)
li $v0, 4
la $a0, prompt2
syscall
jal read_matrix
la $t0, matrix_b
sw $v0, ($t0)
sw $v1, 4($t0)
sw $a0, 8($t0)
sw $a1, 12($t0)
jal multiply_matrices
li $v0, 4
la $a0, result_str
syscall
jal print_matrix
li $v0, 10
syscall
read_matrix:
li $t0, 4
read_loop:
li $v0, 5
syscall
add $v1, $v0, $zero
sub $t0, $t0, 1
bgtz $t0, read_loop
jr $ra
multiply_matrices:
la $t0, matrix_a
la $t1, matrix_b
la $t2, result_matrix
li $t3, 2
li $t4, 2
li $t5, 0
outer_loop:
li $t6, 0
inner_loop:
li $t7, 0
li $t8, 0
row_col_multiply:
lw $t9, 0($t0)
lw $s0, 0($t1)
mul $t9, $t9, $s0
add $t8, $t8, $t9
addi $t0, $t0, 4
addi $t1, $t1, 4
addi $t7, $t7, 1
blt $t7, $t4, row_col_multiply
sw $t8, 0($t2)
addi $t2, $t2, 4
addi $t0, $t0, -8
addi $t1, $t1, -8
addi $t6, $t6, 1
blt $t6, $t4, inner_loop
addi $t0, $t0, 8
addi $t5, $t5, 1
addi $t1, $t1, 8
blt $t5, $t3, outer_loop
jr $ra
print_matrix:
la $t1, result_matrix
li $t3, 2
li $t4, 2
print_row:
li $t5, 0
print_col:
lw $a0, 0($t1)
li $v0, 1
syscall
li $v0, 11
li $a0, 32
syscall
addi $t1, $t1, 4
addi $t5, $t5, 1
blt $t5, $t4, print_col
li $v0, 11
li $a0, 10
syscall
addi $t3, $t3, -1
addi $t1, $t1, -8
bgtz $t3, print_row
jr $ra
.data
matrix_a: .space 16
matrix_b: .space 16
result_matrix: .space 16

Output:

Enter the elements of matrix A (2x2): 55
2
7
2
Enter the elements of matrix B (2x2): 6
2
7
8
Result matrix (2x2) is:
32 32
32 32

The result matrix calculation is wrong.

I tried adding addi $t1, $t1, -8 after addi $t3, $t3, -1 in the print_matrix method. Since I was also having issues with the output even displaying a 2x2 matrix, however, the calculation error still remains.

0

There are 0 best solutions below