Scilab plotting functions with if - function

I have a problen in scilab
How can I plot functions containing if and < like
function y = alpha(t)
if (t < 227.8) then
y = 0.75;
elseif (t < 300) then
y = 2.8 - 0.009 .* t;
else
y = 0.1;
end
endfunction
and
function [r]=minus_alpha(t)
r = 1 - alpha(t)
endfunction
When I use
x = linspace(0,300)
plot(x, alpha(x))
I got the error message
WARNING: Transposing row vector X to get compatible dimensions
plot2d: falsche Größe für Eingangsargument: inkompatible Größen.
Error 999 : in plot2d called by plot
Sorry for german mix. Thank you.

You can avoid explicit loop and be more efficient using the followin code
function y = alpha(t)
y=0.1*ones(t);
y(t<227.8)=0.75;
i=t>=227.8&t<300;
y(i)=2.8 - 0.009 .* t(i);
endfunction

It is really sad to see a great majority of Scilab community is not aware of vectorized operations. You can change your function to:
function y = alpha(t)
y = 0.1;
if t < 227.8 then
y = 0.75;
elseif t < 300 then
y = 2.8 - 0.009 * t;
end
y = 1 - y;
endfunction
and then use feval to broadcast the function over the sequence:
x = linspace(0, 300);
plot2d(x, feval(x, alpha));
which results:
rule of thumb if you are using for loop you need to revise your code and if someone is offering you a code where there is unnecessary for loop you shouldn't probably use it.

All the proposed answers are overcomplicated considering that the function alpha in the original demand is piecewise-affine. In Scilab in can be coded that way:
x = linspace(0,400,1000);
plot(x,linear_interpn(x,[227.8 300],[0.75 0.1]))
i.e. you just have to know the nodes coordinates (here abscissae) and value of the function at nodes. The function linear_interpn does also multilinear interpolation, it is worth knowing it guys...

If you check the output of your alpha(x), you will see that it is just a scalar (not a vector). I guess you wanted something like this, so it's necessary to iterate through t to compute each value of y based on the value of t:
clc;
clear;
function y = alpha(t)
for i=1:size(t,"*")
if t(i) < 227.8 then
y(i) = 0.75;
elseif t(i) < 300 then
y(i) = 2.8 - 0.009 * t(i);
else
y(i) = 0.1;
end
end
endfunction
x = linspace(0,300);
plot2d(x,alpha(x));
If you find the answer useful, please do not forget to accept it, so others will see that your problem is solved.

Before your answers (thank you) my workaround was a combination of indicator functions composed with floor and exp( -t^2):
function y = alpha(t)
y = floor(exp(-(t .* (t-T1)) / (T1*T1))) * 0.75
+ floor(exp(-((t-T2) .* (t- T1) / (2000)))) .* (2.8-0.009 .* t)
+ floor(exp(-((t-T2) .* (t-1000) / (200000))))*0.1
endfunction

Related

Octave, The secant method

I am trying to implement the secant method using Octave, and in particular I made a function called secant("function","x0","x1","tolerance"). I used the while-loop for calculate the root of a function and I think the problem is in the loop.
But the result that I get, it is not what I expect. The correct answer is x=0,49438.
My code is the following:
tol = 10.^(-5); # tolerance
x0 = 0.4; # initial point
x1 = 0.6; # initial point
syms x;
fun = #(x) exp(sin(x)) - 2/(1+x.^2); # f(x) = exp(sin(x)) - 2/(1+x^2)
fprintf("Function f(x)\n");
fun
fprintf("\n");
fprintf("initial points: %f\n",x0,x1);
function[raiz,errel,niter] = secant(fun,x0,x1,tol)
niter = 0; # steps number
errel = []; # the vector of relative errors
y0 = fun(x0); # f(x0)
y1 = fun(x1); # f(x1)
ra = 0.0; # ra is the variable of the function's root
while abs(ra-x1)>= tol
niter += 1;
ra = x1 - ((x1-x0)./(y1-y0)).*y0; # formula of the secant method
if abs((ra-x1))<tol
raiz = ra;
return;
endif
x0 = x1; y0 = y1; x1 = ra;
y1 = fun(ra);
errel(niter) = abs(ra-x1)/abs(ra); # Calcule of relative error
endwhile
if abs((ra-x1)/ra)<tol
fprintf ('The method is over\n');
fprintf ('\n');
endif
raiz = ra;
endfunction
[r,er,tot] = secant(fun,x0,x1,tol)
I appreciate the help you can give me
It makes little sense to use the secant root in the loop condition. At first it is not defined, and inside the loop it is shifted into the support points for the next secant. Note that at the end ra and x1 contain the same value, making the loop condition trivial, in a wrong way.
Next, the secant has the equation
y(x) = y1 + (y1-y0)/(x1-x0)*(x-x_1)
check that with this formula y(x0)=y0 and y(x1)=y1. Thus the secant root is to be found at
x = x1 - (x1-x0)/(y1-y0)*y1
Finally, at no point are symbolic expressions used, defining x as symbolic variable is superfluous.
The break-out test inside the loop is also redundant and prevents a coherent state after the loop. Just remove it and remember that x1 contains the last approximation.
With all this I get an execution log as follows:
Function f(x)
fun =
#(x) exp (sin (x)) - 2 / (1 + x .^ 2)
initial points: 0.400000
initial points: 0.600000
The method is over
r = 0.494379048216965
er =
2.182723270633349e-01 3.747373180587413e-03 5.220701832080676e-05 1.899377363987941e-08
tot = 4

How to pass variadic arguments in Octave

I would like to implement a function duration = timer(n, f, arguments_of_f) that would measure how much time does a method f with arguments arguments_of_f need to run n times. My attempt was the following:
function duration = timer(n, f, arguments_of_f)
duration = 0;
for i=1:n
t0 = cputime;
f(arguments_of_f);
t1 = cputime;
duration += t1 - t0;
end
In another file, I have
function y = f(x)
y = x + 1;
end
The call d1 = timer(100, #f, 3); works as expected.
In another file, I have
function y = g(x1, x2)
y = x1 + x2;
end
but the call d2 = timer(100, #g, 1, 2); gives an error about undefined
argument x2, which is, when I look back, somehow expected, since I pass only
1 to g and 2 is never used.
So, how to implement the function timer in Octave, so that the call like
timer(4, #g, x1, ... , xK) would work? How can one pack the xs together?
So, I am looking for the analogue of Pythons *args trick:
def use_f(f, *args):
f(*args)
works if we define def f(x, y): return x + y and call use_f(f, 3, 4).
You don't need to pack all the arguments together, you just need to tell Octave that there is more than one argument coming and that they are all necessary. This is very easy to do using variadic arguments.
Your original implementation is nearly spot on: the necessary change is minimal. You need to change the variable arguments_to_f to the special name varargin, which is a magical cell array containing all your arbitrary undeclared arguments, and pass it with expansion instead of directly:
function duration = timer(n, f, varargin)
duration = 0;
for i=1:n
t0 = cputime;
f(varargin{:});
t1 = cputime;
duration += t1 - t0;
end
That's it. None of the other functions need to change.

Matlab second order derivative

I have followed the tutorial on http://www.mit.edu/people/abbe/matlab/ode.html and prepared a function as follows:
function dxy = diffxy(xy)
%
%split xy into variables in our equations
%
x = xy(1);
xdot = xy(2);
y = xy(3);
%
% define the derivatives of these variables from equations
%
xdot = xdot;
ydot = 3*x + 2*y + 5;
xdoubledot = 3 - ydot + 2*xdot;
%
%return the derivatives in dxy in the right order
%
dxy = [xdot; xdoubledot; ydot]
end
When I call it using
[T, XY] = ode45('diffxy',0,10,[0 1 0])
I get an error
??? Error using ==> diffxy
Too many input arguments.
I also tried
XY= ode45(#diffxy,[0 10],[0;1;0])
Anybody have any idea?
haven't read the whole tutorial but aren't you supposed to define your function as
function dxy = diffxy(t, xy)
where t is time vector

Solving two coupled non-linear second order differentially equations numerically

I have encountered the following system of differential equations in lagrangian mechanics. Can you suggest a numerical method, with relevant links and references on how can I solve it. Also, is there a shorter implementation on Matlab or Mathematica?
mx (y dot)^2 + mgcosy - Mg - (M=m)(x double dot) =0
gsiny + 2(x dot)(y dot + x (y double dot)=0
where (x dot) or (y dot)= dx/dt or dy/dt, and the double dot indicated a double derivative wrt time.
You can create a vector Y = (x y u v)' so that
dx/dt = u
dy/dt = v
du/dt = d²x/dt²
dv/dt = d²y/dt²
It is possible to isolate the second derivatives from the equations, so you get
d²x/dt² = (m*g*cos(y) + m*x*v² - M*g)/(M-m)
d²y/dt² = -(g*sin(y) - 2*u*v)/x
Now, you can try to solve it using standard ODE solvers, such as Runge-Kutta methods. Matlab has a set of solvers, such as ode23. I didn't test he following, but it would be something like it:
function f = F(Y)
x = Y(1); y = Y(2); u = Y(3); v = Y(4);
f = [0,0,0,0];
f(1) = u;
f(2) = v;
f(3) = (m*g*cos(y) + m*x*v*v - M*g)/(M-m);
f(4) = -(g*sin(y) - 2*u*v)/x;
[T,Y] = ode23(F, time_period, Y0);

How to use Newton-Raphson method in matlab to find an equation root?

I am a new user of MATLAB. I want to find the value that makes f(x) = 0, using the Newton-Raphson method. I have tried to write a code, but it seems that it's difficult to implement Newton-Raphson method. This is what I have so far:
function x = newton(x0, tolerance)
tolerance = 1.e-10;
format short e;
Params = load('saved_data.mat');
theta = pi/2;
zeta = cos(theta);
I = eye(Params.n,Params.n);
Q = zeta*I-Params.p*Params.p';
% T is a matrix(5,5)
Mroot = Params.M.^(1/2); %optimization
T = Mroot*Q*Mroot;
% Find the eigenvalues
E = real(eig(T));
% Find the negative eigenvalues
% Find the smallest negative eigenvalue
gamma = min(E);
% Now solve for lambda
M_inv = inv(Params.M); %optimization
zm = Params.zm;
x = x0;
err = (x - xPrev)/x;
while abs(err) > tolerance
xPrev = x;
x = xPrev - f(xPrev)./dfdx(xPrev);
% stop criterion: (f(x) - 0) < tolerance
err = f(x);
end
% stop criterion: change of x < tolerance % err = x - xPrev;
end
The above function is used like so:
% Calculate the functions
Winv = inv(M_inv+x.*Q);
f = #(x)( zm'*M_inv*Winv*M_inv*zm);
dfdx = #(x)(-zm'*M_inv*Winv*Q*M_inv*zm);
x0 = (-1/gamma)/2;
xRoot = newton(x0,1e-10);
The question isn't particularly clear. However, do you need to implement the root finding yourself? If not then just use Matlab's built in function fzero (not based on Newton-Raphson).
If you do need your own implementation of the Newton-Raphson method then I suggest using one of the answers to Newton Raphsons method in Matlab? as your starting point.
Edit: The following isn't answering your question, but is just a note on coding style.
It is useful to split your program up into reusable chunks. In this case your root finding should be separated from your function construction. I recommend writing your Newton-Raphson method in a separate file and call this from the script where you define your function and its derivative. Your source would then look some thing like:
% Define the function (and its derivative) to perform root finding on:
Params = load('saved_data.mat');
theta = pi/2;
zeta = cos(theta);
I = eye(Params.n,Params.n);
Q = zeta*I-Params.p*Params.p';
Mroot = Params.M.^(1/2);
T = Mroot*Q*Mroot; %T is a matrix(5,5)
E = real(eig(T)); % Find the eigen-values
gamma = min(E); % Find the smallest negative eigen value
% Now solve for lambda (what is lambda?)
M_inv = inv(Params.M);
zm = Params.zm;
Winv = inv(M_inv+x.*Q);
f = #(x)( zm'*M_inv*Winv*M_inv*zm);
dfdx = #(x)(-zm'*M_inv*Winv*Q*M_inv*zm);
x0 = (-1./gamma)/2.;
xRoot = newton(f, dfdx, x0, 1e-10);
In newton.m you would have your implementation of the Newton-Raphson method, which takes as arguments the function handles you define (f and dfdx). Using your code given in the question, this would look something like
function root = newton(f, df, x0, tol)
root = x0; % Initial guess for the root
MAXIT = 20; % Maximum number of iterations
for j = 1:MAXIT;
dx = f(root) / df(root);
root = root - dx
% Stop criterion:
if abs(dx) < tolerance
return
end
end
% Raise error if maximum number of iterations reached.
error('newton: maximum number of allowed iterations exceeded.')
end
Notice that I avoided using an infinite loop.