如何使用Excel VBA创建标识矩阵?

时间:2016-08-05 07:25:29

标签: excel excel-vba vba

我使用这个子例程来创建大小为N

的单位矩阵
Sub IdMatrix()
    Dim i As Integer, j As Integer, N As Integer
    N = 5
    For i = 1 To N
        For j = 1 To N
            If i = j Then
                Cells(i, j) = 1
            Else
                Cells(i, j) = 0
            End If
        Next j
    Next i
End Sub

有更好的方法吗?一个简单的可能吗?

5 个答案:

答案 0 :(得分:2)

从VBA访问工作表非常昂贵。在数组中创建结果应该更快:

Sub idMatrix()
    Dim n As Integer, i As Integer, a() As Integer
    n = 5
    ReDim a(1 To n, 1 To n)
    For i = 1 To n
        a(i, i) = 1
    Next i
    Range("a1").Resize(n, n) = a
End Sub

请注意,将()定义为Integer会使用零启动它(我们可以为零):

答案 1 :(得分:1)

试试这个

Sub IdMatrix1()
Dim N As Long, i As Long
N = 5: Range("A1").Resize(N, N) = 0
    For i = 0 To N - 1
        Range("A1").Offset(i, i) = 1
    Next
End Sub

这是另一种创建单一矩阵的奇怪方法

Sub IdMatrix2()
Dim i As Long, N As Long
N = 5: Range("A1").Resize(N, N) = 0
    For Each cell In Range("A1").Resize(N, N)
        i = i + 1: cell(i) = 1: If i > N - 1 Then Exit For
    Next
End Sub

为了获得最佳性能,请使用受iDevlop回答

启发的代码
Const N = 5             'Put this constant on top of code editor
Sub IdMatrix3()
    Dim IdMx(1 To N, 1 To N) As Long, i As Long
    For i = 1 To N: IdMx(i, i) = 1: Next
    Cells(1,1).Resize(N, N) = IdMx
End Sub

答案 2 :(得分:1)

要获得没有循环的快速子,只需使用以下内容:

Sub test()
  Dim N As Long
  N = 5
  With [A1].Resize(N, N) '<- do not change this A1
    [A1].Resize(N, N).Value2 = Evaluate("IF(ROW(" & .Address & ")=COLUMN(" & .Address & "),1,0)")
  End With
End Sub

答案 3 :(得分:0)

实际上,有一个内置函数MUNIT。只需选择所需的NxN单元格,输入=MUNIT(dimension)并按CTRL+Shift+Enter即可。或者您可以在第一个单元格中键入公式,然后按F2,选择NxN单元格并按CTRL+Shift+Enter

PS。我知道OP可能不会看到这个但也许其他人会这样做。

答案 4 :(得分:0)

IdMx = Application.MUNIT(size)