Where is the error in my below code for approximate solution of poisson boundary value problem? - numerical-methods

I have to solve the following boundary value problem which is
also it is defined in my Matlab code below, but my code doesn't work. I mean I didn't get the approximate solution of my system.
I want to know where is the problem in my code or just the version of matlab that I have can't compile the kind of function I have used , Thanks
Explanation of method I have used : I have used the finite element method or what we called Galerkin Method based on investigation about assembly matrix and stiffness matrix. I have multiplied the system by weight function which satisfies the boundary condition then I have integrated over elements (integration of elementary matrix over the range ]-1,1[). I have four elementary matrix. For more information about that Method I used please check this paper(page:6,7,8)
Note The error I have got upon the compilation of my code is
The current use of "MatElt2Nd" is inconsistent with it previous use or definition in line 7
Code
function [U] = EquaDiff2(n)
% ----------------------------------
% -d²u/dx² + 6*u = (-4*x^2-6)exp(x^2)
% u(-1) = 0 u(1)= 0
%----------------------------------
function [Ke, Fe] = MatElt2Nd(x1,x2)
% déclaration de la fonction,
% function of computing matrix and elementary matrix (assembly matrix)
% ----------------------------------
x = [-1:2/n:1]'; % modification d1 of bound d’intégration
K = zeros(n+1) ;
F = zeros(n+1,1) ;
for i = 1:n
j = i+1;
t = [i j];
x1 = x(i);
x2 = x(j);
[Ke,Fe] = MatElt2Nd(x1,x2);
K(t,t) = K(t,t) + Ke;
F(t) = F(t) + Fe;
end;
K(1,:) = [];
K(:,1) = [];
F(1) = [];
U = K\F;
U = [0.0;U];
t = 0:0.01:1;
return
%-------------------------------------------
% calculation of matrix Ke and vector Fe
%-------------------------------------------
function [Ke,Fe] = MatElt2Nd0(x1,x2)
% NEWly named nested function is introduced
Ke1 = 1/(x2-x1)*[ 1 -1 % no modification done
-1 1 ] ; % essentiellement que les matrices
Ke2 =(x2-x1)* [ 2 1 % élémentaires
1 2 ] ;
N = [(x-x2)/(x1-x2) (x-x1)/(x2-x1)] % function of form
Fe =simple( int(N' * (-4*x^2-6)*exp(x^2) , x, x1, x2) ) % vecteur Fe ;
Ke = Ke1 + 6*Ke2 ;
return
Edit I have got a general code for that but I can't do changes in the general code to solve my system , Any help ?
General Code
% au'(x)+bu"(x)=0 for 0<=x<=d
% BC: u(0)=0 and u(d)=h
%==============================================================
% ======Example======
% Finding an approximate solution to the following BVP using 4 elements of
% equal length.
% u'(x)-u"(x)=0 : 0<=x<=1
% BC: u(0)=0 and u(1)=1
% Solution:
% >> Galerkin(4,1,-1,1,1)
% ==============================================================
% The output of this program is
% 1- The approximate solution (plotted in blue)
% 2- The exact solution (plotted in red)
% 3- The percentage error (plotted in magenta)
%=======================Program Begin==========================
function Galerkin(ne1,a,b,d,h) % Declare function
clc % Clear workspace
% Define the Coefficients of the exact solution
% The Exact solution is : u(x)=C1+C2*exp(-ax/b)
% where C2=h/(exp(-a*d/b)-1)and C1=-C2
C2=h/((exp(-a*d/b))-1);
C1=-C2;
% Define element length
le = d/ne1;
% Define x matrix
x = zeros (ne1+1,1); %
for i=2:ne1 +1
x(i,1) = x(i-1,1)+le;
end
% K1 matrix corresponding to the diffusion term (u"(x))
K1 = (b/le) * [1,-1;-1,1]
% K2 matrix corresponding to the convection term (u'(x))
K2 = a*[-1/2 1/2;-1/2 1/2]
% Element stiffness Matrix
Ke = K1+K2
% Global stiffness matrix
%********************Begin Assembly***************************
k = zeros(ne1+1);
for i=1:ne1+1
for j=1:ne1 +1
if (i==j)
if(i==1)
k(i,j)=Ke(1,1);
elseif(i==ne1+1)
k(i,j)=Ke(2,2);
else
k(i,j)=Ke(1,1)+Ke(2,2);
end
elseif(i==j+1)
k(i,j)=Ke(1,2);
elseif(j==i+1)
k(i,j)=Ke(2,1);
else
k(i,j)=0;
end
end
end
%********************End Assembly*****************************
%The Global f Matrix
f = zeros(ne1+1,1);
%BC apply u(0) = 0
f(1,1) = 0;
%BC apply u(d) = h
f(ne1+1,1) = h;
% Display the Global stifness matrix before striking row
K_Global=k
%Striking first row (u1=0)
k(1,1) = 1;
for i=2:ne1+1
k(1,i) = 0;
k(ne1+1,i) = 0;
end
k(ne1+1,ne1+1) = 1;
% Display the solvable stifness matrix
K_strike=k
%solving the result and finding the displacement matrix, {u}
u=inv(k)*f
hold on
% ======Calculating Approximate Solution and plotting============
syms X
U_sym=sym(zeros(ne1,1));
dU_sym=sym(zeros(ne1,1));
for i=1:ne1
N1x=1-((X-x(i))/le);
N2x=(X-x(i))/le;
U_X=(u(i)*N1x)+(u(i+1)*N2x);
U_sym(i)=U_X;
dU_sym(i)=diff(U_sym(i));
subplot(3,1,1)
hold on
ezplot(U_sym(i),[x(i) x(i+1)])
subplot(3,1,2)
hold on
% du/dx approximate
ezplot(dU_sym(i),[x(i) x(i+1)])
end

Related

Octave: invalid call to a script

I am trying to call to a script, and I am getting an error message. Please help.
The following is what I am trying to run in Octave:
%%% May 23, 2016
%%% Potential Fields for Robot Path Planning
%
%
% Initially proposed for real-time collision avoidance [Khatib 1986].
% Hundreds of papers published on APF
% A potential field is a scalar function over the free space.
% To navigate, the robot applies a force proportional to the
% negated gradient of the potential field.
% A navigation function is an ideal potential field
clc
close all
clear
%% Defining environment variables
startPos = [5,5];
goalPos = [90, 95];
obs1Pos = [50, 50];
obsRad = 10;
goalR = 0.2; % The radius of the goal
goalS = 20; % The spread of attraction of the goal
obsS = 30; % The spread of repulsion of the obstacle
alpha = 0.8; % Strength of attraction
beta = 0.6; % Strength of repulsion
%% Carry out the Potential Field Math as follows:
u = zeros(100, 100);
v = zeros(100, 100);
testu = zeros(100, 100);
testv = zeros(100, 100);
for x = 1:1:100
for y = 1:1:100
[uG, vG] = GoalDelta(x, y, goalPos(1), goalPos(2), goalR, goalS, alpha);
[uO, vO] = ObsDelta(x, y, obs1Pos(2), obs1Pos(1), obsRad, obsS, beta);
xnet = uG + uO;
ynet = vG + vO;
vspeed = sqrt(xnet^2 + ynet^2);
theta = atan2(ynet,xnet);
u(x,y) = vspeed*cos(theta);
v(x,y) = vspeed*sin(theta);
% hold on
end
end
%%
[X,Y] = meshgrid(1:1:100,1:1:100);
figure
quiver(X, Y, u, v, 3)
%% Defining the grid
% Plotting the obstacles
circles(obs1Pos(1),obs1Pos(2),obsRad, 'facecolor','red')
axis square
hold on % Plotting start position
circles(startPos(1),startPos(2),2, 'facecolor','green')
hold on % Plotting goal position
circles(goalPos(1),goalPos(2),2, 'facecolor','yellow')
%% Priting of the path
currentPos = startPos;
x = 0;
while sqrt((goalPos(1)-currentPos(1))^2 + (goalPos(2)-currentPos(2))^2) > 1
tempPos = currentPos + [u(currentPos(1),currentPos(2)), v(currentPos(1),currentPos(2))]
currentPos = round(tempPos)
hold on
plot(currentPos(1),currentPos(2),'-o', 'MarkerFaceColor', 'black')
pause(0.5)
end
The following is the error message I am getting:
error: invalid call to script C:\Users\MyComputer\Downloads\circles.m
error: called from
circles
ECE8743_PotentialFields_Obstacle_1 at line 59 column 1
>>
Here is circles.m:
function [ h ] = circles(x,y,r,varargin)
% h = circles(x,y,r,varargin) plots circles of radius r at points x and y.
% x, y, and r can be scalars or N-D arrays.
%
% Chad Greene, March 2014. Updated August 2014.
% University of Texas Institute for Geophysics.
%
%% Syntax
% circles(x,y,r)
% circles(...,'points',numberOfPoints)
% circles(...,'rotation',degreesRotation)
% circles(...,'ColorProperty',ColorValue)
% circles(...,'LineProperty',LineValue)
% h = circles(...)
%
%% Description
%
% circles(x,y,r) plots circle(s) of radius or radii r centered at points given by
% x and y. Inputs x, y, and r may be any combination of scalar,
% vector, or 2D matrix, but dimensions of all nonscalar inputs must agree.
%
% circles(...,'points',numberOfPoints) allows specification of how many points to use
% for the outline of each circle. Default value is 1000, but this may be
% increased to increase plotting resolution. Or you may specify a small
% number (e.g. 4 to plot a square, 5 to plot a pentagon, etc.).
%
% circles(...,'rotation',degreesRotation) rotates the shape by a given
% degreesRotation, which can be a scalar or a matrix. This is useless for
% circles, but may be desired for polygons with a discernible number of corner points.
%
% circles(...,'ColorProperty',ColorValue) allows declaration of
% 'facecolor' or 'facealpha'
% as name-value pairs. Try declaring any fill property as name-value pairs.
%
% circles(...,'LineProperty',LineValue) allows declaration of 'edgecolor',
% 'linewidth', etc.
%
% h = circles(...) returns the handle(s) h of the plotted object(s).
%
%
%% EXAMPLES:
%
% Example 1:
% circles(5,10,3)
%
% % Example 2:
% x = 2:7;
% y = [5,15,12,25,3,18];
% r = [3 4 5 5 7 3];
% figure
% circles(x,y,r)
%
% % Example 3:
% figure
% circles(1:10,5,2)
%
% % Example 4:
% figure
% circles(5,15,1:5,'facecolor','none')
%
% % Example 5:
% figure
% circles(5,10,3,'facecolor','green')
%
% % Example 6:
% figure
% h = circles(5,10,3,'edgecolor',[.5 .2 .9])
%
% % Example 7:
% lat = repmat((10:-1:1)',1,10);
% lon = repmat(1:10,10,1);
% r = .4;
% figure
% h1 = circles(lon,lat,r,'linewidth',4,'edgecolor','m','facecolor',[.6 .4 .8]);
% hold on;
% h2 = circles(1:.5:10,((1:.5:10).^2)/10,.12,'edgecolor','k','facecolor','none');
% axis equal
%
% % Example 8: Circles have corners
% This script approximates circles with 1000 points. If all those points
% are too complex for your Pentium-II, you can reduce the number of points
% used to make each circle. If 1000 points is not high enough resolution,
% you can increase the number of points. Or if you'd like to draw
% triangles or squares, or pentagons, you can significantly reduce the
% number of points. Let's try drawing a stop sign:
%
% figure
% h = circles(1,1,10,'points',8,'color','red');
% axis equal
% % and we see that our stop sign needs to be rotated a little bit, so we'll
% % delete the one we drew and try again:
% delete(h)
% h = circles(1,1,10,'points',8,'color','red','rot',45/2);
% text(1,1,'STOP','fontname','helvetica CY',...
% 'horizontalalignment','center','fontsize',140,...
% 'color','w','fontweight','bold')
%
% figure
% circles([1 3 5],2,1,'points',4,'rot',[0 45 35])
%
%
% TIPS:
% 1. Include the name-value pair 'facecolor','none' to draw outlines
% (non-filled) circles.
%
% 2. Follow the circles command with axis equal to fix distorted circles.
%
% See also: fill, patch, and scatter.
%% Check inputs:
assert(isnumeric(x),'Input x must be numeric.')
assert(isnumeric(y),'Input y must be numeric.')
assert(isnumeric(r),'Input r must be numeric.')
if ~isscalar(x) && ~isscalar(y)
assert(numel(x)==numel(y),'If neither x nor y is a scalar, their dimensions must match.')
end
if ~isscalar(x) && ~isscalar(r)
assert(numel(x)==numel(r),'If neither x nor r is a scalar, their dimensions must match.')
end
if ~isscalar(r) && ~isscalar(y)
assert(numel(r)==numel(y),'If neither y nor r is a scalar, their dimensions must match.')
end
%% Parse inputs:
% Define number of points per circle:
tmp = strcmpi(varargin,'points')|strcmpi(varargin,'NOP')|strcmpi(varargin,'corners')|...
strncmpi(varargin,'vert',4);
if any(tmp)
NOP = varargin{find(tmp)+1};
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
NOP = 1000; % 1000 points on periphery by default
end
% Define rotation
tmp = strncmpi(varargin,'rot',3);
if any(tmp)
rotation = varargin{find(tmp)+1};
assert(isnumeric(rotation)==1,'Rotation must be numeric.')
rotation = rotation*pi/180; % converts to radians
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
rotation = 0; % no rotation by default.
end
% Be forgiving if the user enters "color" instead of "facecolor"
tmp = strcmpi(varargin,'color');
if any(tmp)
varargin{tmp} = 'facecolor';
end
%% Begin operations:
% Make inputs column vectors:
x = x(:);
y = y(:);
r = r(:);
rotation = rotation(:);
% Determine how many circles to plot:
numcircles = max([length(x) length(y) length(r) length(rotation)]);
% Create redundant arrays to make the plotting loop easy:
if length(x)<numcircles
x(1:numcircles) = x;
end
if length(y)<numcircles
y(1:numcircles) = y;
end
if length(r)<numcircles
r(1:numcircles) = r;
end
if length(rotation)<numcircles
rotation(1:numcircles) = rotation;
end
% Define an independent variable for drawing circle(s):
t = 2*pi/NOP*(1:NOP);
% Query original hold state:
holdState = ishold;
hold on;
% Preallocate object handle:
h = NaN(size(x));
% Plot circles singly:
for n = 1:numcircles
h(n) = fill(x(n)+r(n).*cos(t+rotation(n)), y(n)+r(n).*sin(t+rotation(n)),'',varargin{:});
end
% Return to original hold state:
if ~holdState
hold off
end
% Delete object handles if not requested by user:
if nargout==0
clear h
end
end
What am I doing wrong here? How do I correct this error? I am rather new to Octave and Matlab, so any help is greatly appreciated.
this is the first post after pasting the error so maybe it'll help anyone later:
in my case pasting the script into a function worked out!
function retval = name_of_script(parametres)
%your script
endfunction

Circles.m for Octave

I am a beginner at Octave, and I have limited knowledge of Matlab. Here is what I am trying to do. I am trying to run this script:
%%% May 23, 2016
%%% Potential Fields for Robot Path Planning
%
%
% Initially proposed for real-time collision avoidance [Khatib 1986].
% Hundreds of papers published on APF
% A potential field is a scalar function over the free space.
% To navigate, the robot applies a force proportional to the
% negated gradient of the potential field.
% A navigation function is an ideal potential field
clc
close all
clear
%% Defining environment variables
startPos = [5,5];
goalPos = [90, 95];
obs1Pos = [50, 50];
obsRad = 10;
goalR = 0.2; % The radius of the goal
goalS = 20; % The spread of attraction of the goal
obsS = 30; % The spread of repulsion of the obstacle
alpha = 0.8; % Strength of attraction
beta = 0.6; % Strength of repulsion
%% Carry out the Potential Field Math as follows:
u = zeros(100, 100);
v = zeros(100, 100);
testu = zeros(100, 100);
testv = zeros(100, 100);
for x = 1:1:100
for y = 1:1:100
[uG, vG] = GoalDelta(x, y, goalPos(1), goalPos(2), goalR, goalS, alpha);
[uO, vO] = ObsDelta(x, y, obs1Pos(2), obs1Pos(1), obsRad, obsS, beta);
xnet = uG + uO;
ynet = vG + vO;
vspeed = sqrt(xnet^2 + ynet^2);
theta = atan2(ynet,xnet);
u(x,y) = vspeed*cos(theta);
v(x,y) = vspeed*sin(theta);
% hold on
end
end
%%
[X,Y] = meshgrid(1:1:100,1:1:100);
figure
quiver(X, Y, u, v, 3)
%% Defining the grid
% Plotting the obstacles
circles(obs1Pos(1),obs1Pos(2),obsRad, 'facecolor','red')
axis square
hold on % Plotting start position
circles(startPos(1),startPos(2),2, 'facecolor','green')
hold on % Plotting goal position
circles(goalPos(1),goalPos(2),2, 'facecolor','yellow')
%% Priting of the path
currentPos = startPos;
x = 0;
while sqrt((goalPos(1)-currentPos(1))^2 + (goalPos(2)-currentPos(2))^2) > 1
tempPos = currentPos + [u(currentPos(1),currentPos(2)), v(currentPos(1),currentPos(2))]
currentPos = round(tempPos)
hold on
plot(currentPos(1),currentPos(2),'-o', 'MarkerFaceColor', 'black')
pause(0.5)
end
Here is GoalDelta.m:
% This function gives delX, delY of attraction caused by the goal point
dGoal = sqrt((gx-vx)^2 + (gy-vy)^2); % distance bw goal and current position
thetaG = atan2((gy-vy),(gx-vx)); % angle between goal and current position
% delXG = 0; delYG = 0;
if dGoal<goalR
delXG = 0; delYG = 0;
elseif ((goalS + goalR) >= dGoal) && (dGoal >= goalR)
delXG = alpha*(dGoal - goalR)*cos(thetaG);
delYG = alpha*(dGoal - goalR)*sin(thetaG);
else
delXG = alpha*goalS*cos(thetaG);
delYG = alpha*goalS*sin(thetaG);
end
end
Here is ObsDelta.m:
% This function gives delX, delY of repulsion caused by the obstacle
inf = 10;
dObs = sqrt((ox-vx)^2 + (oy-vy)^2); % distance bw goal and current position
thetaO = atan2((oy-vy),(ox-vx)); % angle between goal and current position
% delXO = 0; delYO = 0;
if dObs<obsRad
delXO = -(sign(cos(thetaO)))*inf;
delYO = -(sign(sin(thetaO)))*inf;
elseif (dObs < (obsS + obsRad)) && (dObs>=obsRad)
delXO = -beta*(obsS + obsRad - dObs)*cos(thetaO);
delYO = -beta*(obsS + obsRad - dObs)*sin(thetaO);
else
delXO = 0;
delYO = 0;
end
end
This is where I am getting the error
*>> circles
error: 'x' undefined near line 112, column 112
error: called from
circles at line 112 column 1*
This is Circles.m that this error comes from. From what I understand, this would not have this error in Matlab, but I cannot afford Matlab. Therefore, I have no way of knowing. In any case, I am trying to figure out how to solve this error.
function [ h ] = circles(x,y,r,varargin)
% h = circles(x,y,r,varargin) plots circles of radius r at points x and y.
% x, y, and r can be scalars or N-D arrays.
%
% Chad Greene, March 2014. Updated August 2014.
% University of Texas Institute for Geophysics.
%
%% Syntax
% circles(x,y,r)
% circles(...,'points',numberOfPoints)
% circles(...,'rotation',degreesRotation)
% circles(...,'ColorProperty',ColorValue)
% circles(...,'LineProperty',LineValue)
% h = circles(...)
%
%% Description
%
% circles(x,y,r) plots circle(s) of radius or radii r centered at points given by
% x and y. Inputs x, y, and r may be any combination of scalar,
% vector, or 2D matrix, but dimensions of all nonscalar inputs must agree.
%
% circles(...,'points',numberOfPoints) allows specification of how many points to use
% for the outline of each circle. Default value is 1000, but this may be
% increased to increase plotting resolution. Or you may specify a small
% number (e.g. 4 to plot a square, 5 to plot a pentagon, etc.).
%
% circles(...,'rotation',degreesRotation) rotates the shape by a given
% degreesRotation, which can be a scalar or a matrix. This is useless for
% circles, but may be desired for polygons with a discernible number of corner points.
%
% circles(...,'ColorProperty',ColorValue) allows declaration of
% 'facecolor' or 'facealpha'
% as name-value pairs. Try declaring any fill property as name-value pairs.
%
% circles(...,'LineProperty',LineValue) allows declaration of 'edgecolor',
% 'linewidth', etc.
%
% h = circles(...) returns the handle(s) h of the plotted object(s).
%
%
%% EXAMPLES:
%
% Example 1:
% circles(5,10,3)
%
% % Example 2:
% x = 2:7;
% y = [5,15,12,25,3,18];
% r = [3 4 5 5 7 3];
% figure
% circles(x,y,r)
%
% % Example 3:
% figure
% circles(1:10,5,2)
%
% % Example 4:
% figure
% circles(5,15,1:5,'facecolor','none')
%
% % Example 5:
% figure
% circles(5,10,3,'facecolor','green')
%
% % Example 6:
% figure
% h = circles(5,10,3,'edgecolor',[.5 .2 .9])
%
% % Example 7:
% lat = repmat((10:-1:1)',1,10);
% lon = repmat(1:10,10,1);
% r = .4;
% figure
% h1 = circles(lon,lat,r,'linewidth',4,'edgecolor','m','facecolor',[.6 .4 .8]);
% hold on;
% h2 = circles(1:.5:10,((1:.5:10).^2)/10,.12,'edgecolor','k','facecolor','none');
% axis equal
%
% % Example 8: Circles have corners
% This script approximates circles with 1000 points. If all those points
% are too complex for your Pentium-II, you can reduce the number of points
% used to make each circle. If 1000 points is not high enough resolution,
% you can increase the number of points. Or if you'd like to draw
% triangles or squares, or pentagons, you can significantly reduce the
% number of points. Let's try drawing a stop sign:
%
% figure
% h = circles(1,1,10,'points',8,'color','red');
% axis equal
% % and we see that our stop sign needs to be rotated a little bit, so we'll
% % delete the one we drew and try again:
% delete(h)
% h = circles(1,1,10,'points',8,'color','red','rot',45/2);
% text(1,1,'STOP','fontname','helvetica CY',...
% 'horizontalalignment','center','fontsize',140,...
% 'color','w','fontweight','bold')
%
% figure
% circles([1 3 5],2,1,'points',4,'rot',[0 45 35])
%
%
% TIPS:
% 1. Include the name-value pair 'facecolor','none' to draw outlines
% (non-filled) circles.
%
% 2. Follow the circles command with axis equal to fix distorted circles.
%
% See also: fill, patch, and scatter.
%% Check inputs:
assert(isnumeric(x),'Input x must be numeric.')
assert(isnumeric(y),'Input y must be numeric.')
assert(isnumeric(r),'Input r must be numeric.')
if ~isscalar(x) && ~isscalar(y)
assert(numel(x)==numel(y),'If neither x nor y is a scalar, their dimensions must match.')
end
if ~isscalar(x) && ~isscalar(r)
assert(numel(x)==numel(r),'If neither x nor r is a scalar, their dimensions must match.')
end
if ~isscalar(r) && ~isscalar(y)
assert(numel(r)==numel(y),'If neither y nor r is a scalar, their dimensions must match.')
end
%% Parse inputs:
% Define number of points per circle:
tmp = strcmpi(varargin,'points')|strcmpi(varargin,'NOP')|strcmpi(varargin,'corners')|...
strncmpi(varargin,'vert',4);
if any(tmp)
NOP = varargin{find(tmp)+1};
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
NOP = 1000; % 1000 points on periphery by default
end
% Define rotation
tmp = strncmpi(varargin,'rot',3);
if any(tmp)
rotation = varargin{find(tmp)+1};
assert(isnumeric(rotation)==1,'Rotation must be numeric.')
rotation = rotation*pi/180; % converts to radians
tmp(find(tmp)+1)=1;
varargin = varargin(~tmp);
else
rotation = 0; % no rotation by default.
end
% Be forgiving if the user enters "color" instead of "facecolor"
tmp = strcmpi(varargin,'color');
if any(tmp)
varargin{tmp} = 'facecolor';
end
%% Begin operations:
% Make inputs column vectors:
x = x(:);
y = y(:);
r = r(:);
rotation = rotation(:);
% Determine how many circles to plot:
numcircles = max([length(x) length(y) length(r) length(rotation)]);
% Create redundant arrays to make the plotting loop easy:
if length(x)<numcircles
x(1:numcircles) = x;
end
if length(y)<numcircles
y(1:numcircles) = y;
end
if length(r)<numcircles
r(1:numcircles) = r;
end
if length(rotation)<numcircles
rotation(1:numcircles) = rotation;
end
% Define an independent variable for drawing circle(s):
t = 2*pi/NOP*(1:NOP);
% Query original hold state:
holdState = ishold;
hold on;
% Preallocate object handle:
h = NaN(size(x));
% Plot circles singly:
for n = 1:numcircles
h(n) = fill(x(n)+r(n).*cos(t+rotation(n)), y(n)+r(n).*sin(t+rotation(n)),'',varargin{:});
end
% Return to original hold state:
if ~holdState
hold off
end
% Delete object handles if not requested by user:
if nargout==0
clear h
end
end

Matlab function in fmincon with fixed value

I have a simple model where I want to minimize the RMSE between my dependent variable y and my model values. The model is: y = alpha + beta'*x.
For minimization, I am using Matlab's fmincon function and am struggling with multiplying my parameter p(2) by x.
MWE:
% data
y = [5.072, 7.1588, 7.263, 4.255, 6.282, 6.9118, 4.044, 7.2595, 6.898, 4.8744, 6.5179, 7.3434, 5.4316, 3.38, 5.464, 5.90, 6.80, 6.193, 6.070, 5.737]
x = [18.3447, 79.86538, 85.09788, 10.5211, 44.4556, 69.567, 8.960, 86.197, 66.857, 16.875, 52.2697, 93.971, 24.35, 5.118, 25.126, 34.037, 61.4445, 42.704, 39.531, 29.988]
% initial values
p_initial = [0, 0];
% function: SEE BELOW
objective = #(p) sqrt(mean((y - y_mod(p)).^2));
% optimization
[param_opt, fval] = fmincon(objective, p_initial)
If I specify my function as follows then it works.
y_mod = #(p) p(1) + p(2).*x
However, it does not work if I use the following code. How can I multiply p(2) with x? Where x is not optimized, because the values are given.
function f = y_mod(p)
f = p(1) + p(2).*x
end
Here is the output from a script that has the function declaration:
>> modelFitExample2a
RMS Error=0.374, intercept=4.208, slope=0.0388
And here is code for the above. It has many commented lines because it includes alternate ways to fit the data: an inline declaration of y_mod(), or a multi-line declaration of y_mod(), or no y_mod() at all. This version uses the multi-line declaration of y_mod().
%modelFitExample2a.m WCR 2021-01-19
%Reply to stack exchange question on parameter fitting
clear;
global x %need this if define y_mod() separately, and in that case y_mod() must declare x global
% data
y = [5.0720, 7.1588, 7.2630, 4.2550, 6.2820, 6.9118, 4.0440, 7.2595, 6.8980, 4.8744...
6.5179, 7.3434, 5.4316, 3.3800, 5.4640, 5.9000, 6.8000, 6.1930, 6.0700, 5.7370];
x = [18.3447,79.8654,85.0979,10.5211,44.4556,69.5670, 8.9600,86.1970,66.8570,16.8750,...
52.2697,93.9710,24.3500, 5.1180,25.1260,34.0370,61.4445,42.7040,39.5310,29.9880];
% initial values
p_initial = [0, 0];
%predictive model with parameter p
%y_mod = #(p) p(1) + p(2)*x;
% objective function
%If you use y_mod(), then you must define it somewhere
objective = #(p) sqrt(mean((y - y_mod(p)).^2));
%objective = #(p) sqrt(mean((y-p(1)-p(2)*x).^2));
% optimization
options = optimset('Display','Notify');
[param_opt, fval] = fmincon(objective,p_initial,[],[],[],[],[],[],[],options);
% display results
fprintf('RMS Error=%.3f, intercept=%.3f, slope=%.4f\n',...
fval,param_opt(1),param_opt(2));
%function declaration: predictive model
%This is an alternative to the inline definition of y_mod() above.
function f = y_mod(p)
global x
f = p(1) + p(2)*x;
end
carl,
The second method, in which you declare y_mod() explicitly (at the end of your script, or in a separate file y_mod.m), does not work because y_mod() does not know what x is. Fix it by declaring x global in the main program at the top, and declare x global in y_mod().
%function declaration
function f = y_mod(p)
global x
f = p(1) + p(2)*x;
end
Of course you don't need y_mod() at all. The code also works if you use the following, and in this case, no global x is needed:
% objective function
objective = #(p) sqrt(mean((y-p(1)-p(2)*x).^2));
By the way, you don't need to multiply with .* in y_mod. You may use *, because you are multiplying a scalar by a vector.

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

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.