7

Is there a built-in way to multiply every member of an array by some number in-place?

Example:

Dim volts () as Double = {1.243, 0.534, 5.343, 2.223, 4.334}
Dim millivolts (4) as Double = volts.MultiplyEachBy(1000) 'something like this
1
  • what version of .net framework are you using? Commented Feb 23, 2010 at 16:43

3 Answers 3

9

You can use the Array.ConvertAll method.

Array.ConvertAll(volts, Function(x) x * 1000)

EDIT

There is a small error in the sample code which needs to be corrected for the above to compile. Remove the explicit size (4) from the variable type

Dim volts() As Double = {1.243, 0.534, 5.343, 2.223, 4.334}
Sign up to request clarification or add additional context in comments.

1 Comment

@Steven, there is a slight error in how you are declaring the variable volts. You need to remove the explicit size 4
0

I don't think there is a built in way to do this, but the best thing I could think to do would be to just create your own method. Something like

Public Function convertMilliamps(ByVal voltArray() As Double)
    For Each item AS Double In voltArray
        item = item * 1000 
    Next

Return voltArray()
End Function

then just do volts = convertMilliamps(volts)

Comments

0

Your function doesn't work for each item because an item is a copy of the value, not the actual item from the array. This should work:

Public Function MultiplyArrayByScalar(ByRef arry As Double(), ByVal scaler As Double) As Double()

    Dim newArry As Double()
    Dim size As Integer = arry.GetLength(0)
    ReDim newArry(size - 1)
    Dim i As Integer
    For i = 0 To size - 1
        newArry(i) = arry(i) * scaler
    Next

    Return newArry
End Function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.