Function ResolMatAC(ByVal MatX As Range, ByVal MatY As Range, ByVal MatXC As Range, ByVal MatYC As Range, Optional ByVal I As Variant = 1)
'Résolution matricielle par la méthode des moindres carrés
'et devant respecter des equations données

'Traitement de l'index
I = CLng(I)

'Tailles matrices
Dim l As Long, L2 As Long, C As Long, C2 As Long
l = MatX.Rows.Count
L2 = MatY.Rows.Count
C = MatX.Columns.Count
C2 = MatY.Columns.Count

Dim LC As Long, L2C As Long, CC As Long, C2C As Long
LC = MatXC.Rows.Count
L2C = MatYC.Rows.Count
CC = MatXC.Columns.Count
C2C = MatYC.Columns.Count

'Erreur de taille
If C <> CC Then ResolMatAC = "#TAILLE!": Exit Function
If C2 > 1 Or C2C > 1 Then ResolMatAC = "#COLONNE!": Exit Function
If l <> L2 Or LC <> L2C Then ResolMatAC = "#LIGNE!": Exit Function
If I > C Then ResolMatAC = "#INDICE!": Exit Function

'calcul la matrice rectangulaire en X
ReDim coefa(1 To l, 1 To C)
Dim t As Long, tt As Long
For t = 1 To l
    For tt = 1 To C
        coefa(t, tt) = MatX.Cells(t, tt)
Next tt, t

'matrice Y
ReDim coefb(l)
For t = 1 To l
    coefb(t) = MatY.Cells(t)
Next t

'Redéfinition matricelle carré selon
'la méthode des moindres carrés
'Matrice X avec reservation eq conditions
ReDim MatA(1 To C + LC, 1 To C + LC)
Dim m As Long, S As Double
For tt = 1 To C
    For m = 1 To C
        S = 0
        For t = 1 To l
            S = S + coefa(t, tt) * coefa(t, m)
        Next t
    MatA(tt, m) = S
Next m, tt

'Redéfinition matricielle carré
'Matrice Y avec reservation eq conditions
ReDim MatB(C + LC, 1)

For tt = 1 To C
    S = 0
    For t = 1 To l
        S = S + coefa(t, tt) * coefb(t)
    Next t
    MatB(tt, 1) = S
Next tt

'Ajonction des eq conditions
'calcul la matrice carré en X
'eq complèments au système
For tt = 1 To CC
    For t = 1 To LC
        MatA(tt, t + C) = MatXC.Cells(t, tt)
Next t, tt
'eq supplémentaires
For t = 1 To LC
    For tt = 1 To CC
        MatA(t + C, tt) = MatXC.Cells(t, tt)
Next tt, t

'matrice Y
For t = 1 To LC
    MatB(t + C, 1) = MatYC.Cells(t)
Next t

'inverse matA et garde la ligne i
ReDim mataa(1, C + LC)
For t = 1 To C + LC
    mataa(1, t) = InverseTabMat(MatA(), I, t)
Next t

'produit deux lignes
ResolMatAC = ProduitTabMat(mataa(), MatB(), 1, 1)

End Function