How to write function correctly - matlab

I'm making a Matlab program for cell growth,
I have a problem with some function in main.m and I found some functions that I thought are written wrong way:
function y = f(c)
y = 0.5*(1-tanh(4*c-2));
function y = h(c)
y = 0.5*f(c);
function y = g(c)
global beta
y = beta*exp(beta*c);
%y=1+0.2*c;
main.m
%%main program
clear; clc;
global alpha beta gamma
%set parameter values
alpha = 0.9; beta = 0.5; gamma = 10;
dx = 1; X = 210; dt = 0.04; T = 16;
c0 = 1;
%set up arrays
x = [dx:dx:X]; Nx = round(X/dx); Nt = round(T/dt);
p = zeros(1,Nx); nextp = zeros(1,Nx);
q = zeros(1,Nx); nextq = zeros(1,Nx);
n = zeros(1,Nx); nextn = zeros(1,Nx);
u = zeros(1,Nx); v = zeros(1,Nx); r = zeros(1,Nx); c = zeros(1,Nx);
P = zeros(Nt,Nx); Q = zeros(Nt,Nx); N = zeros(Nt,Nx);
%set initial values
p = exp(-0.1.*x);
function y = f(c)
y = 0.5*(1-tanh(4*c-2));
function y = h(c)
y = 0.5*f(c);
function y = g(c)
global beta
y = beta*exp(beta*c);
%y=1+0.2*c;
%start FDM time-stepping
for k=1:Nt
r = p + q;
c = (c0.*gamma./(gamma+p)).*(1-alpha.*(p+q+n));
for i=2:Nx-1
u(i)=((p(i+1)-p(i-1))*r(i)*(r(i+1)-r(i-1))+ 4*p(i)*r(i)*...
(r(i+1)-2*r(i)+r(i-1))-p(i)*(r(i+1)-r(i-1))^2)/(2*...
(dx*r(i))^2);
v(i)=((q(i+1)-q(i-1))*r(i)*(r(i+1)-r(i-1))+ 4*q(i)*r(i)*...
(r(i+1)-2*r(i)+r(i-1))-q(i)*(r(i+1)-r(i-1))^2)/(2*...
(dx*r(i))^2);
end
nextp=p+dt.*(u+g(c).*p.*(1-(p+q+n))-f(c).*p);
nextq=q+dt.*(v+f(c).*p-h(c).*q);
nextn=n+dt.*(h(c).*q);
p=nextp;
q=nextq;
n=nextn;
P(k,:)=p; Q(k,:)=q; N(k,:)=n;
end
figure(1)
for n=1:500:Nt
plot(P(n,:),'LineWidth',1.2); hold on;
end
axis([0 270 0 0.6]);
figure(2)
for n=1:500:Nt
plot(Q(n,:),'LineWidth',1.2); hold on;
end
axis([0 270 0 0.6]);
figure(3)
for n=1:500:Nt
plot(N(n,:),'LineWidth',1.2); hold on;
end
axis([0 270 0 1]);
animation.m
%create image for cells
rand('state', sum(100*clock));
prefix='t';
Nm=0;
figure(1)
for n=1:250:Nt
Nm=Nm+1;
for i=1:Nx
tP=round(P(n,i)),tQ=round(Q(n,i)),tN=round(N(n,i));
for m=1:tP
theta=2*pi*rand();
plot(i*sin(theta),i*cos(theta),'b.'); hold on;
end
for m=1:tQ
theta=2*pi*rand();
plot(i*sin(theta),i*cos(theta),'r.'); hold on;
end
for m=1:tN
theta=2*pi*rand();
plot(i*sin(theta),i*cos(theta),'k.'); hold on;
end
axis square
axis([-300 300 -300 300])
end
print('-djpeg','-r100',sprintf('%s_%s',prefix,num2str(Nm)));
end
clear MM
for i=1:Nm
[XX,map]=imread(sprintf('%s_%s',prefix,num2str(i)),'jpeg');
imagesc(XX);
MM(i)=getframe;
pause(0.1);
end
Please help me solve this problem..

You're main.m is a script, not a function (it doesn't start with the word function), see function and Scripts vs. Functions).
In short: function declaration is not allowed in command-line or scripts only in function files.
Do as oro777 advises,
create a seperate file for each function.
Another way is to turn your main.m into a function too, by starting it with function main. Then decleration of additional functions is allowed in the same file, but these are all local functions which means they will only be available from within that file. You can not call them from outside the file they were declared in.

You should write the output error so we can see which function is badly written. At first view, I would say you should use longer function names because with only one letter, it may easily shadow with a variable name and I would advise not to use global variables.
I see that your functions are defined in the same file as the main program, I would advise to create one function per file. For example a f_function m-file with the following code.
function y = f_function(c)
y = 0.5*(1-tanh(4*c-2));
Do the same for your two other functions and place your newly created m-files in the same folder as your main program.

Related

Evaluate a vector in a piecewise function

I want to evaluate the vector xdata in a piecewise function like this:
dat=load('k2.txt');
xdata = dat(:,1);
ydata = dat(:,2);
n=length(xdata);
p0=[0.0821 6.6 0.4];
y(p0,xdata)
function y_hat = y(p,t)
P=4.885;
T0 = 134.27426;
omega=2*pi/P;
gamma1=0.3539 ;gamma2=0.2851;
c1=0;c2=gamma1+2*gamma2;c3=0;c4=-gamma2;
c0=1-c1-c2-c3-c4;
z= p(2).*((sin(omega.*(t-T0))).^2+((p(3)/p(2)).*cos(omega.*(t-T0))).^2).^(1/2);
lambda1= 0;
lambda3=p(1).^2;
if ((1-p(1)<z) & (z<1+p(1)))
k1 = acos((1-p(1).^2 + z.^2)./(2*z));
k0 = acos(((p(1)).^2+z.^2-1)./(2.*z.*p(1)));
y_hat = 1-1./pi*(p(1).^2.*k0+k1-sqrt((4*z.^2-(1+z.^2-p(1).^2).^2)/4));
end
if (1+p(1)<=z)
y_hat=1-lambda1;
end
if (z<=1-p(1))
y_hat=1-lambda3;
end
end
The problem is that the code doesn't enter none of the if loops and returns nothing. Maybe the reason is that the function tries to fulfill the conditions for all the vector at once? How should I proceed so that y(p0,xdata) returns something?
By the way, I need this because I have to fit a model to data like this:
[theta] = lsqcurvefit(#y, p0, xdata, ydata);
Your code doesn't work, because when you write something like this:
if [1 3 -1] > 0
%code
end
Then "%code" won't be evaluated because it's checking, if the condition holds for every value in the vector.
Let's say you want to define the Heaviside function and evaluate a vector of it. Then, what you do is using a for loop:
x_vals = [-1 1 5];
heav(x_vals)
function y = heav(x)
y = zeros(size(x));
for i = 1:length(x)
if x(i) >= 0
y(i) = 1;
else
y(i) = 0;
end
end
end

Solving a system of 6 ode - varying parameter -CLOSED

I am having a system of 6 ode.
What i am trying to manage, is to solve it, for several different values of one of its parameters, parameter 'p', using a for loop at the integration.
I have managed to do it using ode45, however,
using a non-built-in integrator, it seems i am making a mistake and I don't get back the same values, or graphs.
I would appreciate any feedback on my code on what went wrong
Using ODE45
p = -100:+1:350;
time = 0:.05:3;
initial = [0 0 0 0 0 0];
x = NaN(length(time),length(initial),length(p));
for i=1:length(p)
[t,x(:,:,i)] = ode45(#ode,time,initial,[],p(i));
end
figure(1)
plot3(squeeze(x(:,1,:)),squeeze(x(:,2,:)),squeeze(x(:,3,:)))
function dx = ode(~,x,p)
bla bla
end
Using the non-built-in integrator
figure
hold all
for p = -100:+1:350
inicond = [0 0 0 0 0 0];
dt = 0.01;
time = 0:dt:10;
[y] = integrator(#ode,inicond,time,dt,p);
x1 = y(:,1);
x2 = y(:,2);
x3 = y(:,3);
figure(1)
plot3(x1,x2,x3)
axis equal
legend('-DynamicLegend')
end
function [y] = integrator(ode,inicond,time,dt,p)
y = NaN(length(time),length(inicond));
y(1,:) = inicond;
for j=2:length(time)
k1 = dt*ode(y(j-1,:),p);
k2 = dt*ode(y(j-1,:)+k1/2,p);
k3 = dt*ode(y(j-1,:)+k2/2,p);
k4 = dt*ode(y(j-1,:)+k3,p);
y(j,:) = y(j-1,:) + k1/6+k2/3+k3/3+k4/6;
end
end
function [dydt] = ode(y,p)
bla bla
end
Using the non-built-in function to solve Van der Pol for multiple 'epsilon'values: This works., while for the previous it doesnt..
figure
hold all
for epsilon = 0:.2:5
inicond = [0.2 0.8];
dt = 0.1;%timestep for integration
time = 0:dt:100;
[x] = integrator(#VanDerPol,inicond,time,dt,epsilon);
xdot = x(:,2);
x = x(:,1);
figure(1)
plot(x,xdot,'DisplayName',sprintf('epsilon = %1.0f',epsilon))
figure(2)
plot3(time, x,xdot)
axis equal
legend('-DynamicLegend')
end
function [x] = integrator(VanDerPol,inicond,time,dt,epsilon)
x = NaN(length(time),length(inicond));
x(1,:) = inicond;
%%% ACTUAL CALL OF INTEGRATOR %%%%%%%%%%%%%%
for j=2:length(time)
k1 = dt*feval(VanDerPol,x(j-1,:),epsilon);
k2 = dt*feval(VanDerPol,x(j-1,:)+k1/2,epsilon);
k3 = dt*feval(VanDerPol,x(j-1,:)+k2/2,epsilon);
k4 = dt*feval(VanDerPol,x(j-1,:)+k3,epsilon);
x(j,:) = x(j-1,:) + k1/6+k2/3+k3/3+k4/6;
end
end
function [dxdt] = VanDerPol(x,epsilon)
dxdt=NaN(1,2);
dxdt(1,1) = x(:,2);
dxdt(1,2) = epsilon*(1 - x(:,1)^2)*x(:,2) - x(:,1);
end
I am afraid that with the second way, the values of all the repetitions might not be stored correctly and for this reason the values of the occurring matrices after integration, hardly vary one from another

MATLAB: Entering multiple input values for the x-axis in a graph

The MATLAB program below is a function that references specific input values for S, E, r, sigma, and tau.
function [C, Cdelta, P, Pdelta] = ch08(S,E,r,sigma,tau)
% Input arguments: S = asset price at time t
% E = Exercise price
% r = interest rate
% sigma = volatility
% tau = time to expiry (T-t)
%
% Output arguments: C = call value, Cdelta = delta value of call
% P = Put value, Pdelta = delta value of put
%
% function [C, Cdelta, P, Pdelta] = ch08(S,E,r,sigma,tau)
if tau > 0
d1 = (log(S/E) + (r + 0.5*sigma^2)*(tau))/(sigma*sqrt(tau));
d2 = d1 - sigma*sqrt(tau);
N1 = 0.5*(1+erf(d1/sqrt(2)));
N2 = 0.5*(1+erf(d2/sqrt(2)));
C = S*N1-E*exp(-r*(tau))*N2;
Cdelta = N1;
P = C + E*exp(-r*tau) - S;
Pdelta = Cdelta - 1;
title('Graph of Call Value vs. Time to Expiry')
xlabel('Time to expiry')
ylabel('Call Value')
plot (tau,C)
else
C = max(S-E,0);
Cdelta = 0.5*(sign(S-E) + 1);
P = max(E-S,0);
Pdelta = Cdelta - 1;
title('Graph of Call Value vs. Time to Expiry')
xlabel('Time to expiry')
ylabel('Call Value')
plot (tau,C)
end
After running
ch08(3,2.5,0.03,0.25,1)
The following output is produced
After running the function again,
ch08(3,2.5,0.03,0.25,1)
hold on
ch08(3,2.5,0.03,0.25,0.9)
Two data points are produced
After manually typing decreasing tau values,
ch08(3,2.5,0.03,0.25,1)
hold on
ch08(3,2.5,0.03,0.25,0.9)
hold on
ch08(3,2.5,0.03,0.25,0.8)
hold on
ch08(3,2.5,0.03,0.25,0.7)
hold on
ch08(3,2.5,0.03,0.25,0.6)
hold on
ch08(3,2.5,0.03,0.25,0.5)
hold on
ch08(3,2.5,0.03,0.25,0.4)
hold on
ch08(3,2.5,0.03,0.25,0.3)
hold on
ch08(3,2.5,0.03,0.25,0.2)
hold on
ch08(3,2.5,0.03,0.25,0.1)
The graph will produce a bunch of data points,
Is there a way to automate the tau values entered in ch08(S,E,r,sigma,tau) so that the user doesn't have to type all of the input in?
As I suggested in comments, you need to use a for loop. You can create an array with values of tau that you want to use, and call your function with a different element from that array in each loop iteration:
figure, hold on
tau = 10.^(0:-1:-6);
for ii = 1:length(tau)
ch08(3,2.5,0.03,0.25,tau(ii))
end
However, a better solution would be to not plot within your ch08 function, and return the value C as you did in your first version of your question. Then you can do this:
tau = 10.^(0:-1:-6);
C = zeros(size(tau));
for ii = 1:length(tau)
C(ii) = ch08(3,2.5,0.03,0.25,tau(ii));
end
plot(tau,C,'.');
This would allow you to change your plot as you please, for example drawing a line through your points.
PS: Note that you only need to give hold on once. It sets a flag in the figure window that is not cleared until you do hold off or clf.

Pass extra variable parameters to ode15s function (MATLAB)

I'm trying to solve a system of ordinary differential equations in MATLAB.
I have a simple equation:
dy = -k/M *x - c/M *y+ F/M.
This is defined in my ode function test2.m, dependant on the values X and t. I want to trig 'F' with a signal, generated by my custom function squaresignal.m. The output hereof, is the variable u, spanding from 0 to 1, as it is a smooth heaviside function. - Think square wave. The inputs in squaresignal.m, is t and f.
u=squaresignal(t,f)
These values are to be used inside my function test2, in order to enable or disable variable 'F' with the value u==1 (enable). Disable for all other values.
My ode function test2.m reads:
function dX = test2(t ,X, u)
x = X (1) ;
y = X (2) ;
M = 10;
k = 50;
c = 10;
F = 300;
if u == 1
F = F;
else
F = 0,
end
dx = y ;
dy = -k/M *x - c/M *y+ F/M ;
dX = [ dx dy ]';
end
And my runscript reads:
clc
clear all
tstart = 0;
tend = 10;
tsteps = 0.01;
tspan = [0 10];
t = [tstart:tsteps:tend];
f = 2;
u = squaresignal(t,f)
for ii = 1:length(u)
options=odeset('maxstep',tsteps,'outputfcn',#odeplot);
[t,X]=ode15s(#(t,X)test2(t,X,u(ii)),[tstart tend],[0 0],u);
end
figure (1);
plot(t,X(:,1))
figure (2);
plot(t,X(:,2));
However, the for-loop does not seem to do it's magic. I still only get F=0, instead of F=F, at times when u==1. And i know, that u is equal to one at some times, because the output of squaresignal.m is visible to me.
So the real question is this. How do i properly pass my variable u, to my function test2.m, and use it there to trig F? Is it possible that the squaresignal.m should be inside the odefunction test2.m instead?
Here's an example where I pass a variable coeff to the differential equation:
function [T,Q] = main()
t_span = [0 10];
q0 = [0.1; 0.2]; % initial state
ode_options = odeset(); % currently no options... You could add some here
coeff = 0.3; % The parameter we wish to pass to the differential eq.
[T,Q] = ode15s(#(t,q)diffeq(t,q,coeff),t_span,q0, ode_options);
end
function dq = diffeq(t,q,coeff)
% Preallocate vector dq
dq = zeros(length(q),1);
% Update dq:
dq(1) = q(2);
dq(2) = -coeff*sin(q(1));
end
EDIT:
Could this be the problem?
tstart = 0;
tend = 10;
tsteps = 0.01;
tspan = [0 10];
t = [tstart:tsteps:tend];
f = 2;
u = squaresignal(t,f)
Here you create a time vector t which has nothing to do with the time vector returned by the ODE solver! This means that at first we have t[2]=0.01 but once you ran your ODE solver, t[2] can be anything. So yes, if you want to load an external signal source depending on time, then you need to call your squaresignal.m from within the differential equation and pass the solver's current time t! Your code should look like this (note that I'm passing f now as an additional argument to the diffeq):
function dX = test2(t ,X, f)
x = X (1) ;
y = X (2) ;
M = 10;
k = 50;
c = 10;
F = 300;
u = squaresignal(t,f)
if u == 1
F = F;
else
F = 0,
end
dx = y ;
dy = -k/M *x - c/M *y+ F/M ;
dX = [ dx dy ]';
end
Note however that matlab's ODE solvers do not like at all what you're doing here. You are drastically (i.e. non-smoothly) changing the dynamics of your system. What you should do is to use one of the following:
a) events if you want to trigger some behaviour (like termination) depending on the integrated variable x or
b) If you want to trigger the behaviour based on the time t, you should segment your integration into different parts where the differential equation does not vary during one segment. You can then resume your integration by using the current state and time as x0 and t0 for the next run of ode15s. Of course this only works of you're external signal source u is something simple like a step funcion or square wave. In case of the square wave you would only integrate for a timespan during which the wave does not jump. And then exactly at the time of the jump you start another integration with altered differential equations.

Matlab Differential Equations Euler’s method

I need help plotting a differential equation ... it keeps coming out all funky and the graph is not what it's supposed to look like.
function [dydt] = diff(y,t)
dydt = (-3*y)+(t*(exp(-3*t)));
end
tI = 0;
yI = -0.1;
tEnd = 5;
dt = 0.5;
t = tI:dt:tEnd;
y = zeros(size(t));
y(1) = yI;
for k = 2:numel(y)
yPrime = diff(t(k-1),y(k-1));
y(k) = y(k-1) + dt*yPrime;
end
plot(t,y)
grid on
title('Engr')
xlabel('Time')
ylabel('y(t)')
legend(['dt = ' num2str(dt)])
That's my code, but the graph is not anything like what it's supposed to look like. Am I missing something like an index for the for statement?
Edit
I am getting an error:
Error using diff
Difference order N must be a positive integer scalar.
Error in diff3 (line 12)
yPrime = diff(t(k-1),y(k-1));
After fixing the errors pointed out by Danil Asotsky and horchler in the comments:
avoiding name conflict with built-in function 'diff'
changing the order of arguments to t,y.
decreasing the time-step dt to 0.1
converting ODE right-hand side to an anonymous function
(and removing unnecessary parentheses in the function definition), your code could look like this:
F = #(t,y) -3*y+t*exp(-3*t);
tI = 0;
yI = -0.1;
tEnd = 5;
dt = 0.1;
t = tI:dt:tEnd;
y = zeros(size(t));
y(1) = yI;
for k = 2:numel(y)
yPrime = F(t(k-1),y(k-1));
y(k) = y(k-1) + dt*yPrime;
end
plot(t,y)
grid on
title('Engr')
xlabel('Time')
ylabel('y(t)')
legend(['dt = ' num2str(dt)])
which performs as expected: