I am attempting to create an algorithm that finds the trace of an n-by-n square matrix A.the trace of an n-by-n square matrix A is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of A.The main idea involved is that at this level multi-dimensional arrays are stored as one-dimensional arrays, and the multi-dimensional indexing (for a matrix with m rows and n columns) is converted to one-dimensional indexing.As I'am unfamiliar with mips attempts to integrate it into code are unsuccessful my latest attempt below.
I have set the registers to the following:
$a0 = base address of array (matrix), a
$a1 = n, number of rows and columns
$v0 = trace
$t0 = i
trace: move $v0, $zero
move $t0, $zero
bne $t0,$a1,end
sll $t1,$a0,4
add $t1,$t1,$t0
sll $t1,$t1,2
add $t2,$t1,$a0
lw $t0,0($t1)
addi $sp, $sp, 8
sw $t1,0($t0)
j trace
end: jr $ra
but to no avail the answer does not come out as desired the format of the algorithm should be as follows;
trace = 0
for i = 0 to n-1
trace = trace + a[i,i]
end for
I have added some comments indicating suspicious behaviour
trace: move $v0, $zero
move $t0, $zero
loop: bne $t0,$a1,end
sll $t1,$a0,4 ; t1 = a0 * 16, a0 is the base address, should probably be $t0
add $t1,$t1,$t0
sll $t1,$t1,2
add $t2,$t1,$a0
lw $t0,0($t1)
addi $sp, $sp, 8 ; What are you doing with $sp? perhaps this should be add $v0,$v0,$t0
sw $t1,0($t0) ; What are you storing here?
j trace ; This should probably jump to loop, or the code will never end
end: jr $ra
Also note that the sll assumes that the size of your matrix is 16.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.