translating loop from Fortran to MATLAB - matlab

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.

Related

Nesting a specific recursion in Pari-GP

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.

Implemetation of BAT algorithm in Scala

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.

end statement in Matlab takes 50% of time with sample code [duplicate]

So, I've recently started using Matlab's built-in profiler on a regular basis, and I've noticed that while its usually great at showing which lines are taking up the most time, sometimes it'll tell me a large chunk of time is being used on the end statement of a for loop.
Now, seeing as such a line is just used for denoting the end of the loop, I can't imagine how it could use anything other than a trivial amount of processing.
I've seen a specific version of this question asked on matlab central, but a consensus didn't seem to be reached.
EDIT: Here's a minimal example of this problem:
for i =1:1000
x = 1;
x = [x 1];
% clear x;
end
Even if you uncomment the clear, the end line still takes up a lot of computation (about 20%), and the clear actually increases the absolute amount of computation performed by the end line.
When I've seen this in my code, it's been the deallocation of large temporaries created in the loop. Each new variable created in the loop is deallocated at the end.

for loop range syntax

I spent a couple of hours debugging a problem that I would have thought would have been a syntax error.
a = zeros(3);
for i=1:1size(a,2) % note the missing colon between 1 and size(a,2)
i
end
The following only displays
ans = 3
1
Essentially, it seems Matlab/Octave parses the above as:
for i=1:1
size(a,2)
i
end
Note however that
i=1:1size(a,2)
produces a syntax error. Is there a good reason that Matlab/Octave has this for loop syntax? Is there something that it's supposed to make easier? Just curious if anyone else has any thoughts about it. Thanks.
It is indeed a bit of a surprise that Matlab's syntax allows this. I don't know why this is allowed. One reason might be to allow for-loops on one line:
>> for i=1:3 disp(i);end
1
2
3
But interestingly, removing the space is not allowed:
>> for i=1:3disp(i);end
for i=1:3disp(i);end
|
Error: Unexpected MATLAB operator.
This reason for this is probably that a number followed by d is another way of writing a floating point number (3d10 == 3e10), so the parser/tokenizer initially thinks you define a number, but then gets confused when it sees the i. Daniel's example with fprintf does work, since a number followed by an f is not a valid number, so the tokenizer understands that you started a new token.
I guess that many years ago (>30?), when they defined matlab's syntax, they did not foresee that this could introduce this kind of hard-to-spot problems. I guess matlab was originally written by engineers for engineers, and not by someone who knows how to design a general purpose programming language. Other languages like C or Python use punctuation to separate loop conditions from loop body, so there is no ambiguity. I don't know if it is still possible to correct Matlab's syntax, since it might break old code that relies on the current behavior.
At least, if you use a recent version of Matlab, the editor warns for various problems in your code. Paying attention to the small red dashes in the right hand border could have saved you a few hours of debugging time (but maybe you were using octave). I try to make it a habit to fix all the warnings it indicates. For your code, it shows the following:
Your code is equivalent to
a = zeros(3);
for i=1:1
size(a,2)
i
end
There are some places where everyone would use newline or white space, but the parser itself does not require.
A minimal loop:
for i=1:3fprintf('%d',i),end
but I recommend to use at least a comma seperated version, everything else is horrible to read:
for i=1:3,fprintf('%d',i),end

Patch with transparency and timestamp indexes breaks figure

I am having trouble plotting a patch on a figure with transparency and timestamp index varying in datenum range of 735k, which is more or less the datenum you will acquire for the actual dates.
The following example illustrate my issue:
k=[735172.912437674 735172.941375799 0 7830];
figure;
axis(k);
p=patch([k(1) k(1) k(2) k(2)], [k(3) k(4) k(4) k(3)],[0 0 0 0],'r', 'FaceAlpha', 0.1);
Are you able to reproduce this bug? Any suggestions? I've seen this other post and searched about it, but no clue. I wouldn't like to remove the minimum from my time stamps, I would have to adapt all the code just because of this x(
I was learning about this other question and they led me to study a bit the new Handle Graphics that may finally appear this or next year (?) — looks like trying to discovering trends at financial business, guess when this will go out, if it will haha. It may be used by adding -hgVersion 2 option at your matlab launch. And by doing so, the resulting figure looks like this \o/:
Great… but beware that there are some differences on the usage from the HG1 to the HG2 that may lead your code not to work (specially if you are using listeners) but if you want to explore this even more undocumented code add an if in your codes where it breaks:
if feature('UseHG2')
% HG2 approach
else
% HG1 approach
end
One good thing it's that at least we can get the meta.class from the handles, so we can explore them easier x) and the usage is quite more intuitive with the matlab oop development way.