谢谢大家。这是我最后的三嵌套循环和矩阵乘积代码。对于我测试的内容,它适用于任何矩阵和正负值:
void main()
{
unsigned int m = 3; // numero di righe della prima matrice
unsigned int n = 2; // numero di colonne della prima matrice
unsigned int k = 4; // numero di colonne della seconda matrice
short int mat1[] = { -1,-2, 4,5, 4,-2 }; // prima matrice
short int mat2[] = { 2,0,0,0, 0,2,0,0 }; // seconda matrice
int mat3[1024]; // matrice risultato
__asm {
lea eax, mat1 //load mat1
lea edi, mat3 //load mat result
push m
Loop3 : //extern loop
lea ebx, mat2 //load here mat2 to start from the beginning when new result raw starts
xor edx, edx //sets to zero column counter set to zero when new result row starts
Loop2 : //middle loop, as long as k, mat2 columns
xor ecx, ecx //sets to zero mat1 column counter every n multiplications
Loop1 : //inner loop
call Compute //calls sub program that calulates raw/column products
inc ecx //increase column counter
cmp ecx, n //check column counter
jb Loop1 //if below loop1 again
add ebx, 2 //if equal to n, inner loop is over, move mat2 position of one position
inc edx //increase mat2 column counter
cmp edx, k //chek mat2 column counter
jb Loop2 //if below loop2 again
imul esi, n, 2 //else calculate offset to skip to new raw in mat1
add eax, esi //...skip to new mat1 raw
imul esi, k, 4 //calculate offset to skip to new raw in result matrix(mat3)
add edi, esi //...skip to new raw in mat3
dec m //a raw in mat1 has been done, decrease its counter
cmp m, 0 //check how many raws has been done
ja Loop3 //if more than zero, do extern loop again
jmp Finale //else algorithm is over
Compute : //calulates raw/column products
movsx esi, WORD PTR[eax][ecx * 2]
push edi //stores mat3 address to free edi counter
push ecx //stores the actual value of column counter to free ecx register
mov edi, k //calculates the offset in mat2...
imul edi, ecx //...
movsx ecx, WORD PTR[ebx][edi * 2] //mov the value of mat2 to ecx
imul esi, ecx //multiplicates values of mat1 ad mat2
pop ecx //set back column counter
pop edi //set back mat3 address
cmp ecx, 0 //if ecx is zero...
je First //...is the first multiplication for this result value...
add[edi][edx * 4], esi //if not the first, add the value to current position
Back :
ret //in any case, comes back to loops...
First : //...so move here the first value to which add the others
mov[edi][edx * 4], esi //moving value
jmp Back
Finale : //the end
pop m //restore the original mat1 raw value to print the result matrix below
}
//Output on video
{
unsigned int i, j, h;
printf("Product Matrix:\n");
for (i = h = 0; i < m; i++) {
for (j = 0; j < k; j++, h++)
printf("%6d ", mat3[h]);
printf("\n");
}
}
}
这只是我从stackoverflaw中的双嵌套循环开始编写的三嵌套循环的算法:
m = raws of first matrix
k = columns of second matrix
n = column of first matrix and raws of second matrix
x=0
Loop3:
y=0
Loop2:
z=0
Loop1:
compute...
z++
if(z<n)
go to Loop1
y++
if(y < k)
go to Loop2
x++
if(x < m)
go to Loop3
Else go to the End