VBA 数组乘法,逐元素无循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9645490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:29:53  来源:igfitidea点击:

VBA Array multiplication, elementwise without looping

arraysvbaelementmultiplication

提问by Eva

Hi everybody: Following liitle issue:

大家好:以下小问题:

Option Base 1
Sub Test()
Dim aa() As Integer
Dim bb() As Integer
ReDim aa(3)
ReDim bb(3)
For j = 1 To 3
    aa(j) = j * 2
    bb(j) = j * 3
Next j
End Sub

Now the only little thing that I want to do is to multiply the two one dimensional arrays elementwise without looping, and then to unload this new array (6,24,54) in a range. I'm sure this must be easily possible. A solution that I would see is to create a diagonal matrix (array) and then to use mmult, but I'm sure this is doable in a very simple manner. Thanks for the help.

现在我想做的唯一一件小事是不循环地将两个一维数组逐个相乘,然后在一个范围内卸载这个新数组 (6,24,54)。我相信这一定很容易实现。我会看到的一个解决方案是创建一个对角矩阵(数组),然后使用 mmult,但我确信这是以一种非常简单的方式可行的。谢谢您的帮助。

回答by aevanko

There is no way to do multiplication on each element in the array without a loop. Some languages have methods that appear to do just that, but under the hood they are looping.

没有循环就无法对数组中的每个元素进行乘法运算。有些语言的方法似乎就是这样做的,但在底层它们是循环的。

As you've mentioned in your comments, you have 2 choices:

正如您在评论中提到的,您有 2 个选择:

  • Loop through a range and do the multiplication
  • Dump the range into an array, do the multiplication, then dump back onto a range
  • 循环遍历一个范围并进行乘法运算
  • 将范围转储到数组中,进行乘法,然后转储回范围

It all depends on your data, but almost always you'll find that dumping a range into a variant array, doing your work, and dumping it back will be much faster than looping through a range of cells. How you dump it back into a range will also affect the speed, mind you.

这一切都取决于您的数据,但几乎总是您会发现将一个范围转储到一个变体数组中,完成您的工作,然后将其转回将比循环遍历一系列单元格快得多。请注意,您如何将其转回一个范围也会影响速度。

回答by Poisson

It is possible to multiply ranges without explicit looping, e.g. try:

可以在没有显式循环的情况下乘以范围,例如尝试:

sub try()
  [c1:c3].value = [a1:a3 * b1:b3]
end sub

Same logic as in: =sumproduct(a1:A3-b1:b3;a1:A3-b1:b3)

与以下相同的逻辑:=sumproduct(a1:A3-b1:b3;a1:A3-b1:b3)

回答by Dale Myers

I'm not entirely sure that this is possible in any language (with the possible exception of some functional languages). Perhaps if you told us why you wanted to do this we could help you more?

我不完全确定这在任何语言中都是可能的(某些功能语言可能除外)。也许如果您告诉我们您为什么要这样做,我们可以为您提供更多帮助?