I am having problems with a real scalar argument being passed to a Mata function having its value changed by the calling code. In programming terms I would like to pass the argument by value, but instead it is being passed by reference. It is obvious how to do the reverse (pass the pointer and then de-reference it within the called function), but I am stuck with how to pass the value only (i.e perform a bitwise copy to a new memory address). The example and output proving the passed scalar is being modified is included below. Thanks for your help.
when calling the binary search algorithm with
the output looks like
Note that the value of sa.n is the value of sa.x in the previous iteration - that is "max = sa.x" is also assigning the value to sa.n, because that is the value passed as the max argument.
Obviously I can get the function to give me the desired value by calling "BinarySearch(0.02275, 0, 242, sa, &LbBeta())", but generally I would like the scalar arguments passed to a function to remain untouched.
Code:
class searchArgs { public real scalar x,n,p public void toString() } void searchArgs::toString(){ printf("x:%f,n:%f,p:%f",this.x,this.n,this.p); } real scalar BinarySearch( real scalar target, real scalar min, real scalar max, class searchArgs scalar sa, pointer(real scalar function) delegate, | real scalar approx, real scalar maxIts) { real scalar k, val, argLen; argLen = args(); if (argLen<6){ approx = 0.0005; } if (argLen < 7){ maxIts = 200; } for(k=0;k<maxIts;k++){ sa.x = (min+max)/2; val = (*delegate)(sa); //debug tool - remove later sa.toString(); if (val >= .) { return(.); } if ((abs(val-target)<=approx)){ return(sa.x) } if (val<target) { min = sa.x; } else { max = sa.x; } } return(.); } real scalar LbBeta(class searchArgs sa){ return(ibetatail(sa.x+1,sa.n-sa.x, sa.p)) } real scalar UbBeta(class searchArgs sa){ return(1-ibetatail(sa.x,sa.n-sa.x+1, sa.p)) }
Code:
sa = searchArgs() sa.n=242 sa.p=0.0414434 BinarySearch(0.02275, 0, sa.n, sa, &LbBeta())
Code:
x:121,n:242,p:.0414434 1 x:60.5,n:121,p:.0414434 1 x:30.25,n:60.5,p:.0414434 1 x:15.125,n:30.25,p:.0414434 1
Obviously I can get the function to give me the desired value by calling "BinarySearch(0.02275, 0, 242, sa, &LbBeta())", but generally I would like the scalar arguments passed to a function to remain untouched.
Comment