I have implemented BAT Algorithm in Scala (I am interested in functional programming style).Steps involved in BAT algorithm are
Parameters of BAT algorithm are
x : Position of BAT
My Code is working fine without any errors but its output is not desired one as there is no change in position of BAT's after specified iteration. I am wondering where things are wrong in code. My code is below.
I also want to remove while loop so that code become pure functional in style.
I do not know why it is, but it appears that when single stepping through your program that these lines of code reset your positions back to their original values:
if(math.random > j.PulseRate ){
j.position = j.BestPosition + (Bandwidth * sum / N) //sum/d is mean of Loudness , where N is number of BAT's
}
If you comment this block of code out, then your positions do change. As I am not a bat expert, I have no idea if the change is correct or not, but they do change.
Hopefully this is sufficient to debug your algorithm correctly.
Related
everyone!
I've posted a similar problem, initially on Stackexchange; it was moved here and can be found at the link: Declaring a functional recursive sequence in Matlab I'm trying to do something similar in this post, but I've figured that Matlab isn't the place to do it. I'll have to use Pari-GP; and at this point there's no two ways about it.
This is essentially a coding project I've made for myself; which is to effectively numerically evaluate a certain construction of the Tetration function. I've been able to code it fairly well in MatLab; the trouble is, as we are dealing with large numbers like e^e^e^e^e^e^e; these short circuit in MatLab. Pari-GP has a much better understanding of numbers which would usually cause overflows; and I'm now fully realizing why it's used consistently by the Tetration community.
Nonetheless, the Matlab code works for small numbers and numbers with a niceness to them (well placed imaginary argument). For completeness of this question; the github repository for the matlab code is https://github.com/JmsNxn92/Recursive_Tetration This isn't the code we want though; I've optimized it further; this isn't up to date totally. But for the purpose of this question, it's enough.
Now, I'm not the best programmer. I haven't programmed since '09, maybe; but I still know my way around. But it's more that I have the framework of coding; and less the actual syntax. Imagine being well acquainted with french philosophy and french writing; but stumbling your words when ordering a cafe.
As to that, I'll stop beating around the bush, and get to the question.
If I define a function beta_function in Pari-GP and write it as,
beta_function(z,l,n) =
{
out = 0;
for(i=0,n-1,
out = exp(out)/(exp(l*(n-i-z)) +1));
out;
}
Everything is good, and it works. Now the code for beta_function in MatLab isn't very different. There's nothing more complex being added. As I originally asked for MatLab, I'm asking again for Pari-GP. This is how to code a function tau_K(z,l,n,k); which is perfectly doable. I'm just missing something obvious.
The code for tau_K(z,l,n,k) in MatLab is attached below. A friendly person on here explained how to do this in MatLab; for those of you interested, I wasn't really defining the recursion properly beforehand. Here is the current MatLab code I'm using,
function f = tau_K(z,l,n,k)
if k == 1
f = -log(1+exp(-l*z));
return
end
f = log(1 + tau_K(z+1,l,n,k-1)./beta_function(z+1,l,n)) - log(1+exp(-l*z));
end
The question is simple. How would one define this recursion in Pari-GP; how do you code this in Pari-GP?
Everything seems to be collapsing towards a return value at 0, when I try to directly translate this code. And honest to god; I know it's just because I'm making some syntax error in how I'm calling the output into the next iteration. I've tried everything I could think of. And the tutorials, they don't seem to be helping. I've tried next to everything. And at this point, I know I'm missing something stupid syntactically.
I'm just hoping someone here would be so helpful as to explain this to me like I'm in kindergarten. I've heard that tail recursion is important here. And if so, how would I code this in? Simply add in a variable which keeps track of everything?
Again, thanks if you got this far into the question.
When asking questions, it would help if you would provide expected output for some specified given arguments, otherwise it is hard to test. I don't know MATLAB, but your functions could be written in PARI:
beta_function(z,l,n)={
my(out = 0);
for(i=0,n-1,
out = exp(out)/(exp(l*(n-i-z)) +1));
out;
}
tau_K(z,l,n,k)={
if(k == 1,
-log(1+exp(-l*z)),
log(1 + tau_K(z+1,l,n,k-1)/beta_function(z+1,l,n)) - log(1+exp(-l*z))
)
}
In the beta_function, it is important to put my() around out = 0. This keeps the variable local to the function. Failure to do this, means that out will be a global variable, and many subtle bugs can arise.
PARI is a functional programming language which means you often don't need to assign things explicitly to temporary variables. For example if will return a value and this can be returned from your tau_K function (in your MATLAB code you assign to a temporary variable f, but in PARI this is not necessary).
There are no issues with calling a function recursively. In this case, tau_K can just call itself as needed.
In the MATLAB program you have ./. I don't know what this means - I have replaced by / which is just the normal division operator.
Before running you will need to set some precision for the numeric operations. The easiest way to achieve this is to enter \p100 at the PARI-GP prompt. (or \p1000 if you need a 1000 decimal digits of precision). It is possible to control precision dynamically, if you need some part of the calculation performed at high precision and other parts at a lower precision or if the precision needs to be dependent on n.
I have a very simple MATLAB program for training and testing a regression tree, I use the same Data carsmall that is in the tutorial examples:
clear all
clc
close all
load carsmall
X = [Cylinders, Weight, Horsepower, Displacement];
Y = MPG;
tree = fitrtree(X,Y, 'PredictorNames',{'Cylinders', 'Weight', 'Horsepower', 'Displacement'},'ResponseName','MPG','MinLeaf',10);
Xtest=[6,4100,150,130];
MPGest = predict(tree, Xtest);
This gives as a result MPGest=14.9167
I want to know how the predict function is arriving at that value, usually to understand I go line by line inside the function. This one is very tricky because uses classes so I arrive at this line
node = findNode(this.Impl,X,this.DataSummary.CategoricalPredictors,subtrees);
and inside that function I arrive to
n = classreg.learning.treeutils.findNode(X,...
subtrees,this.PruneList,...
this.Children',iscat,...
this.CutVar,this.CutPoint,this.CutCategories,...
this.SurrCutFlip,this.SurrCutVar,...
this.SurrCutPoint,this.SurrCutCategories,...
verbose);
when I try to step in at this step it just give me n=10, how is MATLAB arriving at this number? for example, If I wanted to make my own program to calculate this number using the tree object as input without using predict?
Actually, the function you are looking for is defined into a MEX file. If you try to open it using the open function, you will get the following outcome:
open 'classreg.learning.treeutils.findNode'
Error using open (line 145) Cannot edit the MEX-file
'C:...\toolbox\stats\classreg+classreg+learning+treeutils\findNode.mexw64'
Unfortunately, MEX files are compiled from C++ sources into bytecode (better known as assembly language). There are many decompilers out there that you can use in order to rebuild the instructions compiled into the library (this is a nice starting point, if you want a fast overview), and the whole process is feasible especially because the file itself is quite small.
The code you will get back will not be the original source code, but something similar: variables will have a default and meaningless name, there will be pointers all over and it may also contain bugs due to a wrong reversing of some assembly instructions. This will be probably enough to let you understand what's going on, but you will not be able to follow the computations through a step by step debugging session in Matlab.
Now, the only question you have to answer to is: is this worth the effort?
Pretty simple, and I thought I knew what I was doing, but apparently not. Anyways.
I need to find the first element in a vector that is less than a specific value. Here is the code that I have been using:
t = 0:0.01:5;
u = ((2)*exp(-10.*t).*cos((4.*sqrt(6)).*t) + ((5)./sqrt(6)).*exp(-10.*t).*sin((4.*sqrt(6)).*t));
for a = 1:size(u)
if u(a) < (0.05)
disp(a)
break
end
end
The value that I'm trying to find is the first element less than 0.05, however, when I run my code, I don't get anything.
What could I be doing wrong?
Thanks!
#user2994291 has correctly pointed out where your loop based solution is going wrong (+1).
However I would also add that what you are trying to do can simply be accomplished by:
find(u < 0.05, 1, 'first')
Technically, the third input is not necessary - you could just use:
find(u < 0.05, 1)
However, I seem to recall reading at some point that find will work faster if you provide the third input.
The upper bound of your for loop is probably equal to 1.
In your case, u is a row vector (can't say 100% for sure in MATLAB as I only have access to GNU Octave right now), but calling size(u) will probably give back [1 501] as an answer. Your for-loop will select 1 as upper bound.
Try replacing size(u) with size(u,2) or, even better, with length(u). I get a = 24 as an answer.
Edit:
from your questions I assume you are a MATLAB beginner, therefore I strongly advise you to look into the built-in debugger (you can add breakpoints by clicking on the left vertical bar next to the desired line of code), this would have helped you identify the error with ease and will save you a lot of time in the future.
Say I have a function foo that can return three values given an input:
function [a,b,c] = foo(input)
The calculations of variables b and c take a long time, so sometimes I may wish to ignore their calculation within foo. If I want to ignore both calculations, I simply call the function like this:
output1 = foo(input);
and then include nargout within foo:
if nargout == 1
% Code to calculate "a" only
else
% Code to calculate other variables
The problem occurs if I want to calculate the last output, but not the second. In that case my function call would be:
[output1,~,output3] = foo(input);
Now if I use nargout within foo to check how many outputs are in the function-call, it will always return 3 because the tilde operator (~) is considered a valid output. Therefore, I cannot use nargout to determine whether or not to calculate the second output, b, within foo.
Is there any other way to do this? I.e., is it possible to check which outputs of a function-call are discarded from within the function itself?
The commenters are basically right; this is not something that can be totally solved by the user unless The MathWorks adds functionality. However, I wrote a small function, istilde (Wayback Machine Archive), a while back that attempts to do what you ask. It works in many cases, but it's really a bit of hack and not a totally robust solution. For example, I did not attempt to get it to work for functions called from the Command Window directly (this could potentially be added with some work). Also, it relies on parsing the actual M-file, which can have issues. See the included demo file for how one might use istilde.
Feel free to edit my code for your needs – just don't use this in any production code due to the robustness issues. Any improvements would be welcome.
I'm currently translating code from Fortran to MATLAB manually, and I am unsure of how to translate part of it. (The entire code actually is a 2,000 line subroutine.) The code is below.
C Has series crossed neckline?
120 neckext=x(trough(peaknum-1))+
* dydx*real((t-trough(peaknum-1)))
if(x(t).lt.neckext) goto 130
C NO. Here if series has not crossed neckline, nor new trough found
C Check to see if new trough has been found.
t=t+1
if(t.ge.lastobs) goto 900
if(x(t).lt.min) then
min=x(t)
mindate=t
end if
troughid=min*(1.0+cutoff)
if(x(t).ge.troughid) goto 150
goto 120
C YES. Here if series crossed neckline before new trough found
130 dblcount=0
if(poscount.ge.1) then
DO 132 i=1,poscount
if((enterdt(i)-2.le.t).and.(t.le.enterdt(i)+2)) then
dblcount=dblcount+1
end if
132 continue
if(dblcount.ge.1) then
C write(30,2583) t,Cutnum
2583 format('DoubleCounting episode occurred at ',I5,
* ' with Cutoff = ',F3.1)
goto 150
end if
end if
My problem is with this part of the code:
if(x(t).ge.troughid) goto 150
goto 120
When I was translating this part in MATLAB, I was writing something like:
if x(t,:)>=troughid
t=marker;
minimum=x(t,:);
end
But I don't know what to do with the label 120. When I translate it, do I write that part again? Because from what I understand, when I go back to 120, the code will be running again. Thanks!
EDIT: As a response to Chris's question on what labels 150 and 900 do, I'll post them here.
150 t=marker
min=x(t)
And this is for the label 900.
C Last observation found. This iteration finished.
900 continue
As it should be clear by now, Matlab does not include any variant of a "goto" command. The core Matlab command set appear to be designed around the "structured programming" philosophy. (Which, if I remember my CS ancient history correctly, was the great debate prior to object oriented programming.) Wikipedia has a decent discussion of structured programming.
In the dark days before structured programming, people used to be very excited about flow charts, since that was one of the easiest ways to visualized and understand a piece of code using a lot of goto statements (now usually referred to as spaghetti code).
I suspect that you will need to flowchart the entire subroutine, and then decide which control flow constructs can best be used to recreate your code. If it is a relatively simple diagram, then you should be able to recreate the entire code with if statements or case statements, although a series of small helper functions may be more elegant. If it has a more complex structure, then it may take a little more creativity to translate.
You can wrap the first half of your code, until after the goto 120 in a while loop. You can then break out of this while loop when the condition if(x(t) .lt. neckext) is met. For example, the logic could look something like the following. Note that I have not tried to convert it all to MATLAB (that is your job!!) but hopefully it gets you started.
% Has series crossed neckline?
neckext = x(trough(peaknum-1)) + dydx*real((t-trough(peaknum-1)));
if (x(t) < neckext)
% Code below `goto 120` here...
else
while (x(t) >= neckext)
% Code above `goto 120` here...
end
end
% `goto 150` code here?
I'm not quite sure if the above is what you need, since without the full code I have no idea what goto 150 and goto 900 are supposed to do to the program flow (apart from making it hard to follow).
Almost all allowed goto's in Fortran can be translated into MATLAB by using while/break/continue constructs. I have written a (unreleased) program to automatically remove goto's from Fortran code, then I use my program, f2matlab, to translate the code to MATLAB/Octave.