Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

arrays - ReDim Preserve "Subscript Out of Range"

I am trying to move data from 2 Double Arrays to 2 different Double Arrays. I'm not sure what the size is going to be because I am taking a randomized sample out of the first arrays and putting it into the 2nd arrays.

When I add the ReDim Preserve line I get the Subscript Out of Range error.

Function CreateTrainingSet(TrainingPercent As Double, Inputs() As Double, Outputs() As Double)
 ' Create Randomized Training set data
 Dim TrainingInputs() As Double, TrainingOutputs() As Double
 Dim i As Integer, j As Integer, count As Integer
 'ReDim TrainingInputs(UBound(Inputs, 1), UBound(Inputs, 2))
 'ReDim TrainingOutputs(UBound(Outputs, 1), UBound(Outputs, 2))
 count = 0

 ' Move TraningPercent % of data from Inputs and Outputs to TrainingInputs and TrainingOutputs
 For i = LBound(Inputs, 1) To UBound(Inputs, 1)
  Dim ran As Double
  ran = Rnd()
  If ran <= TrainingPercent Then
   count = count + 1
   For j = LBound(Inputs, 2) To UBound(Inputs, 2)
    ReDim Preserve TrainingInputs(1 To count, 1 To UBound(Inputs, 2))
    TrainingInputs(count, j) = Inputs(i, j)
   Next j
   For j = LBound(Outputs, 2) To UBound(Outputs, 2)
    ReDim Preserve TrainingOutputs(1 To count, 1 To UBound(Outputs, 2))
    TrainingOutputs(count, j) = Outputs(i, j)
   Next j
  End If
 Next i

 For i = LBound(TrainingInputs, 1) To UBound(TrainingInputs, 1)
  For j = LBound(TrainingInputs, 2) To UBound(TrainingInputs, 2)
   Cells(i, j + 10).Value = TrainingInputs(i, j)
  Next j
 Next i


End Function
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To summarise the comments above into an answer:

  • You can only redim the last dimension of a multi dimension array

Therefore in order to resize a multiple dimension array there are a couple of simple options:

  1. If only one dimension needs to be resized flip the loops and logic around so that the dimension to be resized becomes the last dimension
  2. If both dimensions must be resized use either an array of arrays or a collection of arrays and correct the loops as required

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...