MATLAB Error Message (function definitions) - matlab

I am getting the following error when I type in CalculateIntegral(2,5) into the MATLAB Command Window:
??? Error: File: CalculateIntegral.m Line: 2 Column: 1
Function definitions are not permitted at the prompt or in scripts.
I am not sure how to resolve this error. Thanks.
clear all;
function g = CalculateIntegral(s,N)
a=0;
b=1;
h=(b-a)/N;
x = 0:h:1;
g = ff(x).*exp(-s*x);
% compute the exact answer of the integral
exact_answer=antiderivative(b,s)-antiderivative(a,s);
% compute the composite trapezoid sum
If=0;
for i=1:(N-1)
If=If+g(i)*h;
end;
If=If+g(1)*h/2+g(N)*h/2;
If;

You can't have a clear all before your function definition (and you don't need one). Just remove that first line to make your code work. MATLAB functions need to be by themselves in their own file, named like the function (CalculateIntegral.m in your case).

Related

Error: Undefined function or variable "B" when trying to find zeros of a function

I'm having a little trouble evaluating B in the function bidfn. More specifically, I have been unable to find the zeroes of C from the nested function ptesta.
Just for some context, Dmr is the numerical solution to a first-order differential equation at the 101 points in A. srfna and stfna are my attempts to find sr and st in x=K(sr) and B=RR(st) respectively. (As of yet, I have found no way of finding the inverses of K and RR since they can only be solved for numerically.)
My problem is that C is a function of st and stfna takes B as its input. So, anytime I try to evaluate bidfn for a given x I get the following error:
Undefined function or variable "B".
Error in bidfn/stfna (line 72)
if B<=RR(1)
Error in bidfn (line 15)
st=stfna;
I know the issue is that I want to solve for B while B is also an input in stfna. What I’m not sure of is how to get around this issue. I run into the same problem when I use fsolve instead of fzero. Any advice will be greatly appreciated.
Thanks in advance!
My code is as follows:
function B=bidfn(x)
%%% DEFINITIONS
K=Dmr; % this is the solution to the ODE dmr/ds
A=0:0.01:1; % this is the set of points K is solved at
for i=1:101
RR=A+K; % this function combines the two
end
%%% FUNCTION CALLS
fun=#ptesta;
sr=srfna;
st=stfna;
%%% B FUNCTION
if x<0.5
B=0;
elseif x==0.5
B=0.5;
elseif x>=0.5+K(101)
B=x+0.5;
else
x0=[0,1];
B=fzero(fun,x0);
end
%%% NESTED FUNCTIONS
%%% Nested function 1
function C=ptesta
for y=1:101
z1=integral(A(y)+x,0,sr(y));
z2=integral(RR(y),st(y),sr(y));
C=(z1-z2)-B*st(y);
end
end
%%% Nested function 2
function sr=srfna
if x<=K(1)
sr=0;
elseif x>=K(101)
sr=1;
else
for q=2:100
if x>=K(q-1) && x<K(q)
sr=A(q-1);
end
end
end
end
%%% Nested function 3
function st=stfna
if B<=RR(1)
st=0;
elseif B>=RR(101)
st=1;
else
for v=2:100
if B>=RR(v-1) && B<RR(v)
st=A(v-1);
end
end
end
end
%%% END OF NESTED FUNCTIONS
end

Matlab fzero function

If someone could help me answer the following question in matlab it would be greatly appreciated, I'm new to the software and am pretty confused.
Use fzero to approximate a root of sin(x) = cos(2x) near x = 1.
The fzero function expects to get a function handle and a starting point. It's result is the closest point which is a root for the function. In your case, we are looking for the root of cos(2x)-sin(x)=0 near x=1. The code you need is:
fun = #(x)(cos(2*x)-sin(x)); % Create an anonymous function handle.
x0 = 1; % Set a starting point.
res = fzero(fun, x0); % Calculate the nearest root.
Your question equals to finding the zeropoint of a function:
f=cos(2.*x)-sin(x)
First, create new function file for f:
function y = funczero01(x)
%Finding the zeros of the function below
y=cos(2.*x)-sin(x);
endfunction
Save the file with funczero01.m and load it to the path.
Then invoke funczero01 in the debugger window:
x0=fzero('funczero01',1)
x0 = 0.52360
Make sure that you truly understand fzero('func',x0). For more details,check Matlab Document.

Inputting a function on MATLAB

I have been trying to write a MATLAB code that can take in any function for optimization with as many variables as the user wants.
function Enter_Optimization_Code
clear all
clc
x=[];
U='';
n=input('Enter the number of variables= ')
U=input('Enter function with variables as x(1), x(2), x(3)..= ','s')
start=input('Enter coordinates of the starting point as [1,3,..]= ')
for i=1:n
x(i)=start(i)
end
int(U)
The code is asking the user to enter the number of variables they want and then the function they want to optimize (I didnt write the optimization code yet). For now, I want the code to plug in the value of the starting point into the function and spit out the answer.
e.g. I am entering a function that is x(1)+x(2) and start point as [1,2]. This should cause the code to do the calculation of 1+2=3 and print 3. This is what's happening instead:
Enter the number of variables= 2
n =
2
Enter function with variables as x(1), x(2), x(3)..= x(1)+x(2)
U =
x(1)+x(2)
Enter coordinates of the starting point as [1,3,..]= [1,2]
start =
1 2
x =
1
x =
1 2
Undefined function 'int' for input arguments of type 'char'.
Error in Enter_Optimization_Code (line 17)
Can anybody solve this?
If you are trying to integrate the function with the symbolic function int, you can't pass a string input to that function, it has to be a symbolic expression, check the documentation.
You probably need to do int(sym(U)) instead to convert the string U into a symbolic expression.
EDIT based on comments and using TroyHaskin's suggestion
Here's a version that should work. However, I'm not sure why this is a function, it should really be a script.
function Enter_Optimization_Code
% Not sure why you're using a function, this should really be a script
% clear all should only be used in scripts, not in functions
clc
% n=input('Enter the number of variables= '); not needed
U=input('Enter function with variables as x(1), x(2), x(3)..= ','s');
start=input('Enter coordinates of the starting point as [1,3,..]= ');
f = str2func(['#(x)',U]);
y = feval(f,start);
disp([U 'evaluated at x=([' num2str(start) ']) = ' num2str(y)])
If you want the user to enter the equation in this manner, you can convert the string to an anonymous function using str2func:
fun = str2func(['#(x)',U]);
This will work for function literals like x(1)-x(2)^x(3) and valid function calls my_opt(x).

MATLAB - properly defining function and running script

I am trying to write a program for the Bisection method, but I am not fully understanding how to properly define a function and run the script. I have searched google and watched YouTube videos and MATLAB tutorials on this stuff, but I just don't get it. I hope someone here can help me once I present my code, and the error messages I am getting, as well as what I should expect to see...
Code:
function [f] = Bisection(a,b,Nmax,TOL)
f(x)= x^3 - x^2 + x;
i=1;
BisectA=f(a);
while i <= Nmax
p=a+(b-a)/2;
BisectP=f(p);
if BisectP == 0 || (b-a)/2 < TOL
disp('p');
end
i=i+1;
if BisectA*BisectP > 0
a=p;
BisectA=BisectP;
else
b=p;
end
end
disp('Method failed after num2str(Nmax) iterations, Nmax=', Nmax);
When I run this code, I get the error message:
??? Undefined function or variable 'x'.
Error in ==> Bisection at 2
f(x)= x^3 - x^2 + x;
I am unable to figure out how to define 'x'?? Also, should I create more than one function? I would like to have them all in one file.
Thanks.
You error is occurring because x is indeed undefined. If you'r trying to create an anonymous function that takes x as an argument, you'd do that like this:
f = #(x)x.^3-x.^2+x;
Then you can call f(a) as you do later on. Another potential issue is that your Bisection function is returning f. Do you want it to return the function handle?

error in two dimensional secand method

i want to understand what is a error in the following code?code is given below
function x0=secand2d(f,g,x,dx,tol)
% find solution of f(x,y)=0 and g(x,y)=0
for i=1:20
x0=x;
f0=[feval(f,x0),feval(g,x0)];
x0=x+[dx(1),0];
fx=[feval(f,x0),feval(g,x0)];
fx=(fx-f0)/dx(1);
x0=x+[0 dx(2)];
fy=[feval(f,x0),feval(g,x0)];
fy=(fy-f0)/dx(2);
A=[fx;fy]+eps;
x=x+dx;
dx=(-A\f0'-dx')';
if(norm(dx)<tol) ;return; end;
end;
disp(norm(dx));
pause;
end
which represents of two dimensional secant method,where function f and g is defined by following form
f=#(x,y) (x-sin(x+y)); and g=#(x,y) y-cos(x-y);
i have also checked and these to function works fine on it's parameters
f(3,3)
ans =
3.2794
and
g(1,1)
ans =
0
also
x=[0.9 0.9];
dx=[0.1 0.1];
tol=1e-5;
but following code generated such kind of errors
secand2d(f,g,x,dx,tol)
Error using #(x,y)(x-sin(x+y))
Not enough input arguments.
Error in secand2d (line 5)
f0=[feval(f,x0),feval(g,x0)];
please help me to clarify reasons of this errors
You are getting that error because you are passing only x0 to f here:
f0=[feval(f,x0),feval(g,x0)];
f and g are expecting two inputs. You can fix the error like this:
f0=[feval(f,x0,y0),feval(g,x0,y0)];
If there is not a particular reason you are using feval you can do it like this:
f0 = [f(x0, y0) g(x0, y0)];