0

Calling divsig(h) results in changes to h. But divsig is a function that takes a matrix by value and not by reference. How can this happen?

I'm trying to use the sig/divsig functions on matrices of data, for example:

DenseMatrix 4x4-Double ' h before divsig(h)
     0.5       0.5       0.5       0.5
0.568811  0.995811  0.418727  0.987232
 0.65701  0.269138  0.990942   0.99298
0.716466  0.988705   0.98747  0.999909

divsig(h)

DenseMatrix 4x4-Double ' h after divsig
    0.25        0.25        0.25         0.25
0.245265  0.00417185    0.243395    0.0126045
0.225348    0.196703  0.00897602   0.00697036
0.203142   0.0111678   0.0123732  9.14075E-05

Makes no sense to me what so ever, i'm even setting up a new variable called matrix in the function instead of editing 'mat' it's self.

Function divsig(ByVal mat As LinearAlgebra.Double.Matrix)
    Dim matrix = mat
    For _x = 0 To matrix.RowCount() - 1
        For _y = 0 To matrix.ColumnCount() - 1
            matrix(_x, _y) = derivsigmoid(matrix(_x, _y))
        Next
    Next
    Return matrix
End Function


Function sigmoid(ByVal x As Double) As Double
    Return 1 / (1 + Math.Exp(-x))
End Function


Function derivsigmoid(ByVal x As Double) As Double
    Return x * (1 - x)
End Function


Function sig(ByVal mat As LinearAlgebra.Double.Matrix)
    Dim matrix = mat
    For _x = 0 To matrix.RowCount() - 1
        For _y = 0 To matrix.ColumnCount() - 1
            matrix(_x, _y) = sigmoid(matrix(_x, _y))
        Next
    Next
    Return matrix
End Function
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
  • Where is the divsig function being called? What are you doing with `matrix` when it's returned? – Patrick Apr 10 '19 at 17:35
  • In the question's current state there isn't enough information about what's going on with `h` outside of the `divsig` function for your problem to be reproduced. You might get a better response if you provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Patrick Apr 10 '19 at 17:40
  • FYI I edited the question a little to: place the actual question right a the top; make the title a little more focused on the core issue, and put the function in question first in the code snippet. – StayOnTarget Apr 10 '19 at 18:11
  • I think this is a misunderstanding of what ByVal does. Also, the line matrix=mat just copies the reference to the matrix object, not the object itself. – StayOnTarget Apr 10 '19 at 18:11
  • Possible duplicate of [ByRef vs ByVal Clarification](https://stackoverflow.com/questions/4383167/byref-vs-byval-clarification) – StayOnTarget Apr 10 '19 at 18:13

1 Answers1

0

I have fixed it, turns out matrixes are classes which means passing them ByVal passes the reference anyway. I fixed it by replacing the Dim matrix = mat with

Dim matrix As LinearAlgebra.Double.Matrix = LinearAlgebra.Double.Matrix.Build.DenseOfMatrix(mat)

So matrix becomes a copy of mat instead of just giving the same reference a different identifier.