How I can change the variable in this for loop - caml

I've a problem with a loop for. In this program,
let f s =
for i = 0 to ((String.length s) - 1) do
print_char s.[i];
done;;
For some reasons, I want to change the variable i (increase,dicrease) but this variable is not mutable and I don't see how I can change the pointer on the string s. I think to an another function which but I don't know if is the good idea ..

Related

Octave keeps giving results from function although not asked

I created a function in Octave for which I, at this moment, only want one of the possible outputs displayed. The code:
function [pi, time, numiter] = PageRank(pi0,H,v,n,alpha,epsilon);
rowsumvector=ones(1,n)*H';
nonzerorows=find(rowsumvector);
zerorows=setdiff(1:n,nonzerorows); l=length(zerorows);
a=sparse(zerorows,ones(l,1),ones(l,1),n,1);
k=0;
residual=1;
pi=pi0;
tic;
while (residual >= epsilon)
prevpi=pi;
k=k+1;
pi=alpha*pi*H + (alpha*(pi*a)+1-alpha)*v;
residual = norm(pi-prevpi,1);
end
pi;
numiter=k
time=toc;
endfunction
Now I only want numiter returned, but it keeps giving me back pi as well, no matter whether I delete pi;, or not.
It returns it in the following format:
>> PageRank(pi0,H,v,length(H),0.9,epsilon)
numiter = 32
ans =
0.026867 0.157753 0.026867 0.133573 0.315385
To me it seems strange that the pi is not given with its variable, but merely as an ans.
Any suggestions?
I know the Octave documentation for this is not very extensive, but perhaps it gives enough hints to understand that how you think about output variables is wrong.
The call
PageRank(pi0,H,v,length(H),0.9,epsilon)
returns a single output argument, it is equivalent to
ans = PageRank(pi0,H,v,length(H),0.9,epsilon)
ans is always the implied output argument if none is explicitly given. ans will be assigned the value of pi, the first output argument of your function. The variable pi (nor time, nor numiter) in your workspace will be modified or assigned to. These are the names of local variables inside your function.
To obtain other output variables, do this:
[out1,out2,out3] = PageRank(pi0,H,v,length(H),0.9,epsilon)
Now, the variable out1 will be assigned the value that pi had inside your function. out2 will contain the value of time, and out3 the value of numiter,
If you don't want the first two output arguments, and only want the third one, do this:
[~,~,out3] = PageRank(pi0,H,v,length(H),0.9,epsilon)
The ~ indicates to Octave that you want to ignore that output argument.

How to solve a second order differential equation on Scilab?

I need to solve this differential equation using Runge-Kytta 4(5) on Scilab:
The initial conditions are above. The interval and the h-step are:
I don't need to implement Runge-Kutta. I just need to solve this and plot the result on the plane:
I tried to follow these instructions on the official "Scilab Help":
https://x-engineer.org/graduate-engineering/programming-languages/scilab/solve-second-order-ordinary-differential-equation-ode-scilab/
The suggested code is:
// Import the diagram and set the ending time
loadScicos();
loadXcosLibs();
importXcosDiagram("SCI/modules/xcos/examples/solvers/ODE_Example.zcos");
scs_m.props.tf = 5000;
// Select the solver Runge-Kutta and set the precision
scs_m.props.tol(6) = 6;
scs_m.props.tol(7) = 10^-2;
// Start the timer, launch the simulation and display time
tic();
try xcos_simulate(scs_m, 4); catch disp(lasterror()); end
t = toc();
disp(t, "Time for Runge-Kutta:");
However, it is not clear for me how I can change this for the specific differential equation that I showed above. I have a very basic knowledge of Scilab.
The final plot should be something like the picture bellow, an ellipse:
Just to provide some mathematical context, this is the differential equation that describes the pendulum problem.
Could someone help me, please?
=========
UPDATE
Based on #luizpauloml comments, I am updating this post.
I need to convert the second-order ODE into a system of first-order ODEs and then I need to write a function to represent such system.
So, I know how to do this on pen and paper. Hence, using z as a variable:
OK, but how do I write a normal script?
The Xcos is quite disposable. I only kept it because I was trying to mimic the example on the official Scilab page.
To solve this, you need to use ode(), which can employ many methods, Runge-Kutta included. First, you need to define a function to represent the system of ODEs, and Step 1 in the link you provided shows you what to do:
function z = f(t,y)
//f(t,z) represents the sysmte of ODEs:
// -the first argument should always be the independe variable
// -the second argument should always be the dependent variables
// -it may have more than two arguments
// -y is a vector 2x1: y(1) = theta, y(2) = theta'
// -z is a vector 2x1: z(1) = z , z(2) = z'
z(1) = y(2) //first equation: z = theta'
z(2) = 10*sin(y(1)) //second equation: z' = 10*sin(theta)
endfunction
Notice that even if t (the independent variable) does not explicitly appear in your system of ODEs, it still needs to be an argument of f(). Now you just use ode(), setting the flag 'rk' or 'rkf' to use either one of the available Runge-Kutta methods:
ts = linspace(0,3,200);
theta0 = %pi/4;
dtheta0 = 0;
y0 = [theta0; dtheta0];
t0 = 0;
thetas = ode('rk',y0, t0, ts, f); //the output have the same order
//as the argument `y` of f()
scf(1); clf();
plot2d(thetas(2,:),thetas(1,:),-5);
xtitle('Phase portrait', 'theta''(t)','theta(t)');
xgrid();
The output:

ML variables in functions

I can't seem to find a simple answer to this seemingly simple SML question. I have the code:
fun inde(x, y, L) = if null L then nil else
if x=hd(L) then y+1::inde(x,y+1,tl L) else
inde(x,y+1,tl L);
I want y to be a variable outside the function, so it'll be inde(x,L) but have the y still count properly. When I declare it outside the function (to 0), when the function is recursively called, it resets to 0.
If you were to run this current function, it'd produce a list of where ever x is in the list (L).
so inde(1,0,[1,2,2,1,1]) would produce [1,4,5]
Idiomatic structure when using a functional programming style is to define an inner function that takes arguments that are of interest to the programmer, but not the user and then to call the inner function from the main function:
fun inde(x : int, L) =
let
fun inner(list1, list2, y : int) =
if null list1
then List.rev list2
else
if x = hd list1
then
inner(tl list1, y::list2, y + 1)
else
inner(tl list1, list2, y +1)
in
inner(L,[],1)
end
In the example function:
inner uses four values: the local variables list1,list2, and y. It also uses x from the enclosing scope.
inner builds (conses up) the list that will be returned using list2. It reverses the list with a call to List.rev from the SML Basis Library. This adds O(n) to the execution time.
The last part of the let...in...end construct: inner(L,[],1) is called "the trampoline" because the code gets all the way to the bottom of the source file and then bounces off it to start execution. It's a standard pattern.
Note that I started iterating with y equal to 1, rather than 0. Starting at zero wasn't getting anything done in the original file.

F# Function doesn't let me mutate mutable value

Probably another dumb F# beginner's question... But it's bugging me all the same
I can't seem to find any answers to this online... might be 'cause I search the wrong terms but eh
anyway my code goes as follows:
let counter() =
let mutable x = 0
let increment(y :int) =
x <- x + y // this line is giving me trouble
printfn "%A" x // and this one too
increment // return the function
Visual Studio is telling me that x is used in an invalid way, that mutable variables can't be captured by closures
why is that? and what can I do to allow me to mutate it?
As the error message indicates, you can use a ref cell instead:
let counter() =
let x = ref 0
let increment(y :int) =
x := !x + y // this line is giving me trouble
printfn "%A" !x // and this one too
increment // return the function
This does exactly what your code would do if it were legal. The ! operator gets the value out of the ref cell and := assigns a new value. As to why this is required, it's because the semantics of capturing a mutable value by a closure have proven to be confusing; using a ref cell makes things somewhat more explicit and less error-prone (see http://lorgonblog.wordpress.com/2008/11/12/on-lambdas-capture-and-mutability/ for further elaboration).

Pointer to MATLAB function?

So I have a for-loop in MATLAB, where either a vector x will be put through one function, say, cos(x).^2, or a different choice, say, sin(x).^2 + 9.*x. The user will select which of those functions he wants to use before the for-loop.
My question is, I dont want the loop to check what the user selected on every iteration. Is there a way to use a pointer to a function, (user defined, or otherwise), that every iteration will use automatically?
This is inside a script by the way, not a function.
Thanks
You can use function_handles. For your example (to run on all available functions using a loop):
x = 1:10; % list of input values
functionList = {#(x) cos(x).^2, #(x) sin(x).^2 + 9*x}; % function handle cell-array
for i=1:length(functionList)
functionOut{i} = functionList{i}(x); % output of each function to x
end
You can try something like the following:
userChoice = 2;
switch userChoice
case 1
myFun = #(x) sin(x).^2 + 9.*x;
case 2
myFun = #(x) cos(x).^2;
end
for k = 1:10
x(k,:) = myFun(rand(1,10));
end