MATLAB Simpson's 1/3 Rule and Romberg - matlab

I'm just starting to learn MATLAB.
The purpose of the exercise is to approximate/integrate using Simpson's 1/3 rule and romberg. The problem is to integrate x^(1/2) from 0 to 2
When I execute: simpson(fun,0,2,10)
I get an error on line 2: fun = x^(1/2);
or on line 16 of simpson: f = feval(fun,x);
Thanks for the help!
Here is my equation code:
function [fun] = ff(x)
fun = x^(1/2);
end
My simpson code:
function I = simpson(fun,a,b,npanel)
% Multiple Segment Simpson's rule
%
% Synopsis: I = simpson(fun,a,b,npanel)
%
% Input: fun = (string) name of m-file that evaluates f(x)
% a, b = lower and upper limits of the integral
% npanel = number of panels to use in the integration
% Total number of nodes = 2*npanel + 1
%
% Output: I = approximate value of the integral from a to b of f(x)*dx
n = 2*npanel + 1; % total number of nodes
h = (b-a)/(n-1); % stepsize
x = a:h:b; % divide the interval
f = feval(fun,x); % evaluate integrand
I = (h/3)*( f(1) + 4*sum(f(2:2:n-1)) + 2*sum(f(3:2:n-2)) + f(n) );
% f(a) f_even f_odd f(b)
My romberg code:
function [R,quad,err,h]=romberg(fun,a,b,n,tol)
%Input - fun is the integrand input as a string 'fun'
% - a and b are upper and lower limits of integration
% - n is the maximum number of rows in the table
% - tol is the tolerance
%Output - R is the Romberg table
% - quad is the quadrature value
% - err is the error estimate
% - h is the smallest step size used
M=1;
h=b-a;
err=1;
J=0;
R=zeros(4,4);
R(1,1)=h*(feval(fun,a)+feval(fun,b))/2;
while((err>tol)&(J<n))|(J<4)
J=J+1;
h=h/2;
s=0;
for p=1:M
x=a+h*(2*p-1);
s=s+feval(fun,x);
end
R(J+1,1)=R(J,1)/2+h*s;
M=2*M;
for K=1:J
R(J+1,K+1)=R(J+1,K)+(R(J+1,K)-R(J,K))/(4^K-1);
end
err=abs(R(J,J)-R(J+1,K+1));
end
quad=R(J+1,J+1);

Related

Linear Congruential generator graph

I implemented a simple code for a linear congruential generator
clear all; clc
% Input
m = 59; % module
a = 17; % multiplier
c = 43; % increase
X0 = 27; % seed
n = 100; % sample length
y = [X0 zeros(1,n-1)];
% recursive formula
% X(n+1) = (a*X(n) + c) mod m
for i = 2:n
y(i) = mod(a*y(i-1)+c,m);
end
x = 0:1:n-1;
%for i = 1:n
% plot(x,y);
%end
What I would like to do is a plot where each time the period repeats it draws a vertical line upward as in this graph
I think I have to use the plot function inside a FOR loop and an IF-ELSE to see if the value of the subsequence X(n) is equal to the seed X(0) but I have no idea how to implement it
I think I have to use the plot function inside a FOR loop and an IF-ELSE to see if the value of the subsequence X(n) is equal to the seed X(0) but I have no idea how to implement it

Falsi method algorithm

I wrote a falsi method code and I got problem with fa function. My general function is in interval [a,b]=[2,12], as I defined in main script:
a=2;
b=12;
%Function
syms x real;
f=1.2*sin(x)+2*log(x+2)-5;
I wonder how to correctly pass argument a to the function fa and, in general, to falsi method function . I guess, it cannot be just '2', it must be dynamic somehow. Thanks for tips ! :)
function [ x ] = task1_falsi( f, x, a)
% Defining functions
a=2;
fa=feval(f,a);
f=inline(f);
fa=inline(fa);
err=1;
% Falsi's loop.
% Stops when error is negligible or number of iterations becomes prohibitive
it=0;
while (it<1000) && (err>10e-5)
% Falsi's algorithm
x1=x-feval(f,x)*(x-a)/fa;
% Calculating error
err=abs(x1-x);
% New zero is previous value
x=x1;
it=it+1;
%Showing steps
fprintf('%d\t%f \n',it, x);
end
disp('Root:');
disp(x);
disp('Iterations:');
disp(it);
end
%Task 1
% Falsi's method algorithm
function [ x ] = task1_falsi( f, x)
err=1;
y = 7; % Starting point
z = 8;
f=inline(f);
% Ending point
maxIteration = 1000; % Maximum number of iterations
epsilon = 0.001; % Accuracy
it=0; % Vector with number of iterations
xold = z; % Variable used for calculations
solutionRegulaFalsix=zeros(10,1); % Error vector
for j=0:20
while (it <= maxIteration)
x1 = y - ((feval(f,y)*(z-y))/(feval(f,z)-feval(f,y))); % Calculating the root
it= it+ 1;
if (abs(x1-xold)<epsilon*abs(x1)) % Accuracy condition
break;
else
xold = x1;
if feval(f,y)*feval(f,z) > 0
y = x1; % Starting point is being changed
else
z = x1; % Ending point is being changed
end
end
end
err = abs(x1-x); % Calculating the error
% epsilon = epsilon/10;
%Showing steps
fprintf('%d\t%f \n',it, x);
y=2;
z=3;
disp('Root:');
disp(x1);
disp('Iterations:');
disp(it);
end
end

Taylor series approximation when the series is truncated after the first, second and third term, in MATLAB

I want to write an m-file function demoTaylorlog(x0,dx) that does the equivalent but for the Taylor series representation of f(x) = ln(x).
This is what I have, but it does not work. I am not sure if it is the right code. How should I fix it?
function demoTaylorlog(x0,dx)
% demoTaylor Taylor Series approximations for f(x) = 1/(1-x)
%Synopsis:
% demoTaylorlog(x0,dx)
% Input: x0 = (optional) point about which the Taylor Series expansion is
% made. Default: x0 = 1.6;
% dx = (optional) size of neighborhood over which the expansion
% is evaluated. Default: dx = 0.8
% Output: a plot of f(x) and its Taylor Series approximations
if nargin<2, x0 = 1.6; dx = 0.8; end
x = linspace(x0-dx/2,x0+dx/2,20);
% x-values at which f(x) is evaluated
f(x)= log(x);
% Exact f(x); notice the array operator
h = x - x0;
% Avoid recomputing intermediate values,
t = 1/(1-x0);
% h and t p1x = t*ones(size(x)) + h*t^2;
% First order Taylor polynomial p2x = p1x+ (h.^2)*t^3;
% Second order " " " p3x = p2x + (h.^3)*t^4;
% Third
plot(x,fx,'-',x,p1x,'o-',x,p2x,'^-',x,p3x,'s-');
legend('exact','P_1(x)','P_2(x)','P_3(x)',4);
xlabel('x');
ylabel('Approximations to f(x) = 1/(1-x)');
end
In the statement f(x)= log(x); f is a vector and log is a function. Suppose that your x vector is [0.12 0.24 0.36] then the statement with the error is equivalent to:
f(0.12) = log(0.12);
f(0.24) = log(0.24);
f(0.36) = log(0.36);
But if fis a vector the assignment to f(0.12) has no sense because .12 is not a positive integer or a logical value (as the error says).
You should write f = log(x);

Finite difference - wave equation - boundary conditions and setting things up

I am working on a project that has to do with solving the wave equation in 2D (x, y, t) numericaly using the central difference approximation in MATLAB with the following boundary conditions:
The general assembly formula is:
I understand some of the boundary conditions (BC), like
du/dy=0 at j=m,
,
but I am not sure how to implement these boundary conditions in MATLAB.
A friend has given me these equations:
Here is my try with the MATLAB code,
but I am not able to progress any further:
% The wave function
% Explicit
% Universal boundary conditions for all 3 cases:
% u=0 at t=0
% du/dt=0 at t=0
% Case 1 boundary conditions
% At x=0, u=2sin(2*pi*t/5);
% At y=0, du/dy=0;
% At y=2, du/dy=0;
% At x=5, du/dx=0;
% u=0 and du/dt=0 at t=0;
%-------------------------------------------------------------------------%
% Setting up
clc; clear all; close all;
% length, time, height
L = 5; % [m]
h = 2; % [m]
T = 10; % [s]
% Constants
c_x = 1; % arbitrary
c_y = 1; % arbitrary
dx = 0.1; % <x> increment
dy = 0.1; % <y> increment
dt = 0.1; % time increment
nx = L/dx + 1; % number of <x> samples
ny = h/dy + 1; % number of <y> samples
nt = T/dt + 1; % number of time samples
t(:,1) = linspace(0, T, nt);
theta_x = c_x*(dt^2)/(dx^2);
theta_y = c_y*(dt^2)/(dy^2);
% theta_x = theta_y
theta = theta_x;
%-------------------------------------------------------------------------%
% The matrix
U = zeros(nt, nx, ny);
% Setting up the <U> matrix with the boundary conditions - case 1
U(1, :, :) = 0; % U=0 at t=0
for tt=1:nt % U=2sin(2pi/5*t) at x=0
for jj=1:ny
U(tt, 1, jj)=2*sin(2*pi/5.*t(tt));
end
end
for it=2:t
for ix=2:nx-1
for iy=2:ny-1
% Boundary conditions
% General case (internal):
U1 = -U(it-1, ix, iy);
U2 = 2*(1-2*theta)*u(it, ix, iy);
U3 = theta*U(it, ix-1, iy);
U4 = theta*U(it, ix+1, iy);
U5 = theta*U(it, ix, iy-1);
U6 = theta*U(it, ix, iy+1);
end
end
end
The general assembly formula you have kind of applies to the boundaries as well.
The complication is that when you apply the formula when j = 1 and j = m, you have j = 0 and j = m+1 term that are off of your grid.
To ameliorate this problem, boundary conditions give you a relationship between the points off the grid and on the grid.
As you have indicated, the dudy = 0 condition has given you the relation that u(i,m-1) == u(u,m+1) on the boundary. So you use the general assembly formula and replace all of the m+1 terms with m-1 on the boundary. You'll have a similar relation for the lower boundary as well.

Revised Simplex Method - Matlab Script

I've been asked to write down a Matlab program in order to solve LPs using the Revised Simplex Method.
The code I wrote runs without problems with input data although I've realised it doesn't solve the problem properly, as it does not update the inverse of the basis B (the real core idea of the abovementioned method).
The problem is only related to a part of the code, the one in the bottom of the script aiming at:
Computing the new inverse basis B^-1 by performing elementary row operations on [B^-1 u] (pivot row index is l_out). The vector u is transformed into a unit vector with u(l_out) = 1 and u(i) = 0 for other i.
Here's the code I wrote:
%% Implementation of the revised Simplex. Solves a linear
% programming problem of the form
%
% min c'*x
% s.t. Ax = b
% x >= 0
%
% The function input parameters are the following:
% A: The constraint matrix
% b: The rhs vector
% c: The vector of cost coefficients
% C: The indices of the basic variables corresponding to an
% initial basic feasible solution
%
% The function returns:
% x_opt: Decision variable values at the optimal solution
% f_opt: Objective function value at the optimal solution
%
% Usage: [x_opt, f_opt] = S12345X(A,b,c,C)
% NOTE: Replace 12345X with your own student number
% and rename the file accordingly
function [x_opt, f_opt] = SXXXXX(A,b,c,C)
%% Initialization phase
% Initialize the vector of decision variables
x = zeros(length(c),1);
% Create the initial Basis matrix, compute its inverse and
% compute the inital basic feasible solution
B=A(:,C);
invB = inv(B);
x(C) = invB*b;
%% Iteration phase
n_max = 10; % At most n_max iterations
for n = 1:n_max % Main loop
% Compute the vector of reduced costs c_r
c_B = c(C); % Basic variable costs
p = (c_B'*invB)'; % Dual variables
c_r = c' - p'*A; % Vector of reduced costs
% Check if the solution is optimal. If optimal, use
% 'return' to break from the function, e.g.
J = find(c_r < 0); % Find indices with negative reduced costs
if (isempty(J))
f_opt = c'*x;
x_opt = x;
return;
end
% Choose the entering variable
j_in = J(1);
% Compute the vector u (i.e., the reverse of the basic directions)
u = invB*A(:,j_in);
I = find(u > 0);
if (isempty(I))
f_opt = -inf; % Optimal objective function cost = -inf
x_opt = []; % Produce empty vector []
return % Break from the function
end
% Compute the optimal step length theta
theta = min(x(C(I))./u(I));
L = find(x(C)./u == theta); % Find all indices with ratio theta
% Select the exiting variable
l_out = L(1);
% Move to the adjacent solution
x(C) = x(C) - theta*u;
% Value of the entering variable is theta
x(j_in) = theta;
% Update the set of basic indices C
C(l_out) = j_in;
% Compute the new inverse basis B^-1 by performing elementary row
% operations on [B^-1 u] (pivot row index is l_out). The vector u is trans-
% formed into a unit vector with u(l_out) = 1 and u(i) = 0 for
% other i.
M=horzcat(invB,u);
[f g]=size(M);
R(l_out,:)=M(l_out,:)/M(l_out,j_in); % Copy row l_out, normalizing M(l_out,j_in) to 1
u(l_out)=1;
for k = 1:f % For all matrix rows
if (k ~= l_out) % Other then l_out
u(k)=0;
R(k,:)=M(k,:)-M(k,j_in)*R(l_out,:); % Set them equal to the original matrix Minus a multiple of normalized row l_out, making R(k,j_in)=0
end
end
invM=horzcat(u,invB);
% Check if too many iterations are performed (increase n_max to
% allow more iterations)
if(n == n_max)
fprintf('Max number of iterations performed!\n\n');
return
end
end % End for (the main iteration loop)
end % End function
%% Example 3.5 from the book (A small test problem)
% Data in standard form:
% A = [1 2 2 1 0 0;
% 2 1 2 0 1 0;
% 2 2 1 0 0 1];
% b = [20 20 20]';
% c = [-10 -12 -12 0 0 0]';
% C = [4 5 6]; % Indices of the basic variables of
% % the initial basic feasible solution
%
% The optimal solution
% x_opt = [4 4 4 0 0 0]' % Optimal decision variable values
% f_opt = -136 % Optimal objective function cost
Ok, after a lot of hrs spent on the intensive use of printmat and disp to understand what was happening inside the code from a mathematical point of view I realized it was a problem with the index j_in and normalization in case of dividing by zero therefore I managed to solve the issue as follows.
Now it runs perfectly. Cheers.
%% Implementation of the revised Simplex. Solves a linear
% programming problem of the form
%
% min c'*x
% s.t. Ax = b
% x >= 0
%
% The function input parameters are the following:
% A: The constraint matrix
% b: The rhs vector
% c: The vector of cost coefficients
% C: The indices of the basic variables corresponding to an
% initial basic feasible solution
%
% The function returns:
% x_opt: Decision variable values at the optimal solution
% f_opt: Objective function value at the optimal solution
%
% Usage: [x_opt, f_opt] = S12345X(A,b,c,C)
% NOTE: Replace 12345X with your own student number
% and rename the file accordingly
function [x_opt, f_opt] = S472366(A,b,c,C)
%% Initialization phase
% Initialize the vector of decision variables
x = zeros(length(c),1);
% Create the initial Basis matrix, compute its inverse and
% compute the inital basic feasible solution
B=A(:,C);
invB = inv(B);
x(C) = invB*b;
%% Iteration phase
n_max = 10; % At most n_max iterations
for n = 1:n_max % Main loop
% Compute the vector of reduced costs c_r
c_B = c(C); % Basic variable costs
p = (c_B'*invB)'; % Dual variables
c_r = c' - p'*A; % Vector of reduced costs
% Check if the solution is optimal. If optimal, use
% 'return' to break from the function, e.g.
J = find(c_r < 0); % Find indices with negative reduced costs
if (isempty(J))
f_opt = c'*x;
x_opt = x;
return;
end
% Choose the entering variable
j_in = J(1);
% Compute the vector u (i.e., the reverse of the basic directions)
u = invB*A(:,j_in);
I = find(u > 0);
if (isempty(I))
f_opt = -inf; % Optimal objective function cost = -inf
x_opt = []; % Produce empty vector []
return % Break from the function
end
% Compute the optimal step length theta
theta = min(x(C(I))./u(I));
L = find(x(C)./u == theta); % Find all indices with ratio theta
% Select the exiting variable
l_out = L(1);
% Move to the adjacent solution
x(C) = x(C) - theta*u;
% Value of the entering variable is theta
x(j_in) = theta;
% Update the set of basic indices C
C(l_out) = j_in;
% Compute the new inverse basis B^-1 by performing elementary row
% operations on [B^-1 u] (pivot row index is l_out). The vector u is trans-
% formed into a unit vector with u(l_out) = 1 and u(i) = 0 for
% other i.
M=horzcat(u, invB);
[f g]=size(M);
if (theta~=0)
M(l_out,:)=M(l_out,:)/M(l_out,1); % Copy row l_out, normalizing M(l_out,1) to 1
end
for k = 1:f % For all matrix rows
if (k ~= l_out) % Other then l_out
M(k,:)=M(k,:)-M(k,1)*M(l_out,:); % Set them equal to the original matrix Minus a multiple of normalized row l_out, making R(k,j_in)=0
end
end
invB=M(1:3,2:end);
% Check if too many iterations are performed (increase n_max to
% allow more iterations)
if(n == n_max)
fprintf('Max number of iterations performed!\n\n');
return
end
end % End for (the main iteration loop)
end % End function
%% Example 3.5 from the book (A small test problem)
% Data in standard form:
% A = [1 2 2 1 0 0;
% 2 1 2 0 1 0;
% 2 2 1 0 0 1];
% b = [20 20 20]';
% c = [-10 -12 -12 0 0 0]';
% C = [4 5 6]; % Indices of the basic variables of
% % the initial basic feasible solution
%
% The optimal solution
% x_opt = [4 4 4 0 0 0]' % Optimal decision variable values
% f_opt = -136 % Optimal objective function cost