矩阵的力量

时间:2011-11-27 08:57:34

标签: vba excel-vba excel

如何编写一个VBA宏,它将获取位于单元格A1到C3中的矩阵(用户指定的任意功率)的功能?

3 个答案:

答案 0 :(得分:5)

在数学意义上逐字地提出你的问题,这个宏通过重复调用Excel的MMULT函数将矩阵提升为幂(在示例中为4)。

Dim i As Long
Dim pow As Long
Dim vIn As Variant
Dim vOut As Variant

pow = 4 ' or whatever

' Fetch matrix from sheet
vIn = Range("A1:C3")
' Raise to power
vOut = vIn
For i = 1 To pow - 1
    vOut = WorksheetFunction.MMult(vOut, vIn)
Next i
' Write result to sheet
Range("E1:G3") = vOut

答案 1 :(得分:0)

我使用了以下功能。请注意,当指数为0时,函数返回单位矩阵,否则矩阵乘以指数次数。

'Raises matrix to a power
Function PowerMatrixNew(rngInp As Range, lngPow As Integer) As Variant()
 'create identitu for power 0
 Dim identity() As Variant
 ReDim identity(rngInp.Rows.Count, rngInp.Rows.Count)

 Dim i As Integer
 Dim j As Integer
 For i = 1 To rngInp.Rows.Count
  For j = 1 To rngInp.Rows.Count
   If (i = j) Then
    identity(i, j) = 1
   Else
    identity(i, j) = 0
   End If
  Next j
 Next i

 PowerMatrixNew = identity
 For i = 1 To lngPow
    PowerMatrixNew = Application.WorksheetFunction.MMult(rngInp, PowerMatrixNew)
 Next
End Function

答案 2 :(得分:-1)

几年前有一个像这样的问题,我记得因为它被称为矩阵运算,但不像我在学校教过的那样。

用数字1到9填充单元格A1:C3。将单元格A5设置为2.选择单元格A7:C9并键入

  =power(A1:C3,A5) ctrl+shift+enter

并且单元格A7:C9将被设置为A1:C3中的值的平方。将A5更改为3,将单元格A7:C9设置为A1:C3中值的多维数据集。

VBA中的等价物是:

 Range("a7:c9").FormulaArray = "=Power(a1:c3, a5)"