Averaging solutions in monte carlo simulation using Octave - octave

I am writing a code to find the solution to the Laplacian with a given set of boundary conditions using a Monte Carlo simulation in Octave. I have written the initial code to find single solutions, but this needs to be run quite a few times and then averaged to get a nice, smooth solution. That is the part I need help with, as I don't have a clue how to go about it. The code I have written is:
a=20;
s=1
for (m=s:s:a-s);
for (n=s:s:a-s);
x=m;
y=n;
for (i=1:5000)
R=randi(4);
if (R==1)
xnew=x+s;
ynew=y;
elseif (R==2)
xnew=x-s;
ynew=y;
elseif (R==3)
xnew=x;
ynew=y+s;
elseif (R==4)
xnew=x;
ynew=y-s;
endif
%hold on;
%figure(1);
%plot([x xnew],[y ynew])
x=xnew;
y=ynew;
if (x==0);
u(n,m)=sin(pi*y/a);
break
elseif (x==a);
u(n,m)=0;
break
elseif (y==0);
u(n,m)=0;
break
elseif (y==a);
u(n,m)=0;
break
else
continue;
endif
endfor
endfor
endfor
figure(2);
contour(u)
In other words, what I want to do is record this value of "u" (the solution), run the program again, record that value of "u", and continue with this process a hundred times or so, then average them out and contour plot the average solution. I am fairly new to scripting, so any advice you can give would be greatly appreciated.
Thanks,
Steve

Why don't you just put it into another loop and store variables?
av_u=0;
count=0;
for i=1:hundred times
%>>>your code to get u here<<<
av_u=av_u+u;
count=count+1;
end
av_u=av_u/count;

Related

What's the proper use of output property in Octave?

I am not sure what is the use of output while using fminunc.
>>options = optimset('GradObj','on','MaxIter','1');
>>initialTheta=zeros(2,1);
>>[optTheta, functionVal, exitFlag, output, grad, hessian]=
fminunc(#CostFunc,initialTheta,options);
>> output
output =
scalar structure containing the fields:
iterations = 11
successful = 10
funcCount = 21
Even when I use max no of iteration = 1 still it is giving no of iteration = 11??
Could anyone please explain me why is this happening?
help me with grad and hessian properties too, means the use of those.
Given we don't have the full code, I think the easiest thing for you to do to understand exactly what is happening is to just set a breakpoint in fminunc.m itself, and follow the logic of the code. This is one of the nice things about working with Octave, since the source code is provided and you can check it freely (there's often useful information in octave source code in fact, such as references to papers which they relied on for the implementation, etc).
From a quick look, it doesn't seem like fminunc expects a maxiter of 1. Have a look at line 211:
211 while (niter < maxiter && nfev < maxfev && ! info)
Since niter is initialised just before (at line 176) with the value of 1, in theory this loop will never be entered if your maxiter is 1, which defeats the whole point of the optimization.
There are other interesting things happening in there too, e.g. the inner while loop starting at line 272:
272 while (! suc && niter <= maxiter && nfev < maxfev && ! info)
This uses "shortcut evaluation", to first check if the previous iteration was "unsuccessful", before checking if the number of iterations are less than "maxiter".
In other words, if the previous iteration was successful, you don't get to run the inner loop at all, and you never get to increment niter.
What flags an iteration as "successful" seems to be defined by the ratio of "actual vs predicted reduction", as per the following (non-consecutive) lines:
286 actred = (fval - fval1) / (abs (fval1) + abs (fval));
...
295 prered = -t/(abs (fval) + abs (fval + t));
296 ratio = actred / prered;
...
321 if (ratio >= 1e-4)
322 ## Successful iteration.
...
326 nsuciter += 1;
...
328 endif
329
330 niter += 1;
In other words, it seems like fminunc will respect your maxiters ignoring whether these have been "successful" or "unsuccessful", with the exception that it does not like to "end" the algorithm at a "successful" turn (since the success condition needs to be fulfilled first before the maxiters condition is checked).
Obviously this is an academic point, since you shouldn't even be entering this inner loop when you couldn't even make it past the outer loop in the first place.
I cannot really know exactly what is going on without knowing your specific code, but you should be able to follow easily if you run your code with a breakpoint at fminunc. The maths behind that implementation may be complex, but the code itself seems fairly simple and straightforward enough to follow.
Good luck!

Octave efficient way to repeat an array

Hi I have a 2D array in Octave, called Sig in the code, and I want to replicate this repeatedly to form a certain number of cycles of this array. The way I've written is working but very slow, am I missing a trick to speed this up?
Cycles=262800
Sig_1=Sig
for i=1:1:Cycles-1;
Sig_1=[Sig_1;Sig];
endfor
You can use repmat:
Sig_1 = repmat(Sig, [Cycles, 1])

Octave: How to solve a one order differential equation with variable coefficients

I'm trying to solve a one order differential equation with variable coefficients of the following form:
xdot(1)=a(t)*x(1)+b;
where b=a constant and where a(t) = a time dependent function. I know that I can solve this equation by hand butt a(t) is a quite complex function.
So, my problem is the following. a(t) is a function which I know its values from an experiment (I've got all the results in a file) --> a(t) is a vector (n x 1) which is a problem because x(1)= xdot(1)=a scalar. So, how could I solve this equation, with lsode ?
Possibly I have underestimated your problem, but the way I read it, you are asking to integrate a first order ODE. In general there are two ways to proceed,, implicit methods and explicit methods. Here is the crudest, but easiest to understand, method I can come up with:
nt=101;a=-ones(1,nt);b=1/2;x=NaN*ones(1,nt);x(1)=pi;dt=0.01;
for kt=2:nt
dxdt=a(kt-1)*x(kt-1)+b;
x(kt)=x(kt-1)+dxdt*dt;
endfor
plot(x)
I have assumed a<0 so there is no tendency to blow up. You will want to set it equal to your observed values.

Simple examples for using while loops

I'm trying to write up some examples to explain when a while loop should be used, and when a for loop should be used.
When looking for 'interesting' cases to show young and novice programmers, I realized that the vast majority of textbook examples for while loops will look something like this:
i = 0
while i < 10:
do something
i = i + 1
'do something' might be printing the odd numbers, squaring i, etc... However all these are obviously easier written with a for loop!
I'm looking for more interesting examples. They would have to be:
Suitable for younger programmers (e.g. not too much math such as numerical root finding or the sequence in Collatz conjecture)
Easier (or more intuitive) to be solved with while loops rather than for.
Have some real use to it (e.g. I could do while random() < 0.95, but what's a real use for this?)
The only example I could come up with is when getting a list input from the user one-by-one (e.g. numbers to be summed), but the user will have to terminate it with a special input, and also this seems pointless as the user could just say in advance how many entries there will be in the sequence.
The fundamental difference between a FOR loop and a WHILE loop is that for a FOR loop, the number of iterations is bounded by a constant that is known before the loop starts, whereas for a WHILE loop, the number of iterations can be unbounded, unknown, or infinite.
As a result, a language offering only WHILE loops is Turing-complete, a language offering only FOR loops is not.
So, the first obvious thing that only a WHILE loop can do, is an infinite loop. Things that are easily modeled as infinite loops are, for example, a web server, a Netflix client, a game loop, a GUI event loop, or an operating system:
WHILE (r = nextHttpRequest):
handle(r)
END
WHILE (p = nextVideoStreamPacket):
frame = decode(p)
draw(frame)
END
WHILE (a = playerAction):
computeNextFrame(a)
END
WHILE (e = nextEvent):
handle(e)
END
WHILE (s = sysCall):
process(s)
END
A good example where the loop is not infinite, but the bound is not known in advance, is (as you already mentioned in your question) asking for user input. Something like this:
WHILE (askBoolean("Do you want to play again?")):
playGame()
END
Another good example is processing a C-like string, where the length of the string is unknown but finite. This is the same situation for a linked list, or for any data structure where there is a notion of "next", but not a notion of "size", instead there is some sentinel value that marks the end (e.g. NUL-terminated strings in C) or a way to check whether there is a next element (e.g. Iterator in Java):
WHILE ((element = getNext()) != END_MARKER):
process(element)
END
WHILE (hasNextElement):
process(getNext())
END
There are also situations that can be handled with a FOR loop, but a WHILE loop is more elegant. One situation I can think of, is that the bound for the number of iterations is known in advance, it is constant, but the known bound is ridiculously large, and the actual number of iterations required is significantly less than the bound.
Unfortunately, I cannot come up with a good real-life example of this, maybe someone else can. A FOR loop for this will then typically look like this, in order to skip the iterations from the actual number of iterations up to the upper bound:
FOR (i FROM 1 TO $SOME_LARGE_UPPER_BOUND):
IF (terminationConditionReached):
NOOP()
ELSE:
doSomethingInteresting()
END
END
Which would much better be expressed as
WHILE (NOT terminationConditionReached):
doSomethingInteresting()
END
Using the FOR loop could make sense in this situation, if the value of i is of interest:
FOR (i FROM 1 TO $SOME_LARGE_UPPER_BOUND):
IF (terminationConditionReached):
NOOP()
ELSE:
doSomethingInterestingWithI(i)
END
END
A last situation I can think of, where a WHILE loop is more appropriate than a FOR loop, even though the number of iterations is bounded by a known constant, is if that constant is not "semantically interesting" for the loop.
For example, a game loop for Tic-Tac-Toe only needs at most 9 moves, so it could be modeled as a FOR loop:
FOR (i FROM 1 TO 9):
IF (player1Won OR player2Won):
NOOP
ELSE:
makeMove()
END
END
But, the number "9" is not really interesting here. It's much more interesting whether one player has one or the board is full:
WHILE (NOT (player1Won OR player2Won OR boardFull)):
makeMove()
END
[Note: at least if playing against a child, this is also an example of the second-to-last situation, namely that the upper bound is known to be 9, but a lot of games will be shorter than 9 moves. However, I would still like to find an example for that, which is not also an example of a semantically un-interesting termination condition.]
So, we have two classes of situations here: one, where a FOR loop simply cannot be used (when the bound is unknown, non-existant, or infinite), and one, where a FOR loop can be used, but a WHILE loop is more intention-revealing.

Octave specgram generates two diffent answers

I have a project where I have to recognize the frequency from an audio file. For this I use a single tone of 10 kHz to see if I can get it working.
Since I am pretty new to Octave, I tried this example with my own audio file.
I tried to understand what happens by doing some research to all functions.
My question here is; if I let specgram plot the figure when I do not specify it's output:
specgram(y,fftn,Fs,hanning(window),step);
it gives a line at 10kHz which is what I want.
But if I specify the output for the specgram function
[S,f,t]= specgram(y,fftn,Fs,hanning(window),step);
and let it plot, it plots the line at 18 kHz.
I figured it have to be in the inputs for the figure and I tried modifying these a bit, but every time I do that Octave gives an error.
I need the frequency as an given output, since I have to do some calculations with it, I figured I need to specify the frequency output.
This is the part of the code that specify the plot for the spectrogram:
step= fix(5*Fs/1000); % stepsize of the window
window= fix(90*Fs/1000); % window size
fftn =2^nextpow2(window); % Size of the FFT block
[S,f,t]= specgram(y,fftn,Fs,hanning(window),step);
S= abs(S(2:fftn*12000/Fs,:)); % Normalize the phase
S= S/max(S(:)); % Normalize the Energy
S= max(S, 10^(-40/10)); % Throw out values below -40 dB and above -3dB
S= min(S, 10^(-3/10));
figure
imagesc(t,f,(log(S)));
Can anyone help me here how to gain the frequency data from the audio file so I can use it in some calculations?
I have searched for answers already in the Octave manual for help and I tried it with various matlab sites. Also checked already many posts here such as:
How does Octave spectrogram 'specgram' from signal work?
Methodology of FFT for Matlab spectrogram / short time Fourier transform functions
P.S. Sorry for my bad English, it's not my native language
I found the answer myself, it turns out it is in this line of code:
S= abs(S(2:fftn*12000/Fs,:));
if I delete this line, the lines are placed on the right frequency in the figure. To me it looks like this line just takes a small space of the fft and replaces it with other frequencies but I'm not shure about that.