Matlab fzero function - matlab

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.

Related

How to write code to run a function and retrieve values from it

I am supposed to use a 2D Gaussian function which will have the following mathematical expression 𝐺(π‘₯) = 𝑒^(βˆ’(π‘₯βˆ’πœ‡)^2/𝑠𝑑𝑑^2) and plot a graph of the function. Β΅ is the mean and std stands for the standard deviation, by the way. How would a write code to plug in values to the function and output the values of G(x) and x in to an array to be plotted?
I've tried looking at older code I've done for previous graph's I've made, but this function is much more complex than I've ever done.
The following anonymous function would work in your case
G = #(x,mu,sigma) exp(-((x-mu).^2)/(sigma^2));
x=-10:0.01:10;
plot(x,G(x,0.2,0.4));
Generically speaking, use the following method to call a function and return values:
Main Script
clc; clear; close all;
x = 0;
y = add_x(x);
Function Call
function y = add_x(x)
y = x+1;
end
Read more about function calling in the MATLAB Documentation.

Solve a matrix valued differential equation in Matlab

I am trying to solve a particular system of ODE's dF/dt = A*F, F_initial = eye(9). Being a Matlab novice, I am trying to somehow use the implemented ode45 function, and I found useful advises online. However, all of them assume A to be constant, while in my case the matrix A is a function of t, in other words, A changes with each time step.
I have solved A separately and stored it in a 9x9xN array (because my grid is t = 0:dt:2, N=2/dt is the number of time-steps, and A(:,:,i) corresponds to it's value at the i-th time step). But I can't implement this array in ode45 to eventually solve my ODE.
Any help is welcomed, and please tell me if I have missed anything important while explaining my problem. Thank you
First of all, F must be a column vector when using ode45. You won't ever get a result by setting F_initial = eye(9), you'd need F = ones(9,1).
Also, ode45 (documentation here, check tspan section) doesn't necessarily evaluate your function at the timesteps that you give it, so you can't pre-compute the A matrix. Here I'm going to assume that F is a column vector and A is a matrix which acts on it, which can be computed each timestep. If this is the case, then we can just include A in the function passed to ode45, like so:
F_initial = ones(9,1);
dt = 0.01;
tspan = 0:2/dt:2;
[t, F] = ode45(#(t,F) foo(t, F, Ainput), tspan, F_initial);
function f = foo(t, F, Ainput)
A = calculate_A(t, Ainput);
f = A*F;
end
function A = calculate_A(t, Ainput)
%some logic, calculate A based on inputs and timestep
A = ones(9,9)*sqrt(t)*Ainput;
end
The #(x) f(x,y) basically creates a new anonymous function which allows you to treat y as a constant in the calculation.
Hope this is helpful, let me know if I've misunderstood something or if you have other questions.

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).

Error with recursive function in m-file

I'm working on chapter 8 of A Course in Mathematical Biology. The textbook uses Maple, but includes this link, Computer course of Chapter 8 in Matlab. I'm told to put the following in an m-file:
% defining a recursive function in an m-file
function y = plot_traj(a)
RM = inline('a*x.*exp(-x)', 'a', 'x')
% Note that we are using an inline function. Sometimes it’s easier to do this.
% collecting list of x-coordinates
for i = 1:31,
X(i) = i - 1
end
% collecting list of y-coordinates
for i = 1:30,
Y(i+1)=RM(a,iter(i));
iter(i+1) = Y(i+1);
end
y = plot(X, Y, '*');
Now, save your m-file (as plot traj.m) and close it. Type the following into the command window:
>> plot traj(0.8)
>> plot traj(1.0)
>> plot traj(5.0)
>> plot traj(8.0)
>> plot traj(13.0)
>> plot traj(14.5)
>> plot traj(20.0)
However, when I type plot traj(0.8) into the command window I get this:
>> plot_traj(0.8)
Undefined function or variable "iter".
Error in plot_traj (line 13)
Y(i)=RM(a,iter(i));
I don't see anything wrong with line 13, and I've made sure that my code is exactly what is in the chapter. I've been doing fine with the codes up until this point. I'd appreciate it if anyone could provide some assistance. Thank you.
The problem at line 13 is that the iter local variable array has not been defined. So on the first iteration, the code tries to access iter(1) and fails. I looked at the link you provided and they missed it too. Based on previous examples in the Matlab_Course.pdf (and figure 8.6), the iter array should be initialized as
iter(1) = 1.0;
Just add this line prior to the for loop and you should be good to continue. I suspect also that this line should be added too (again based on the document)
Y(1)=iter(1);
to make sure that both iter and Y have the same length.
Note that it is a good habit to pre-allocate memory to arrays to avoid the internal resizing of matrices/arrays on each iteration of the loop (which can have a negative impact on performance). For this loop
for i = 1:30,
Y(i+1)=RM(a,iter(i));
iter(i+1) = Y(i+1);
end
you can observe that i iterates over 1 through 30, and we always populate Y(i+1) and iter(i+1). So both Y and iter are 31x1 vectors. We can allocate memory to each prior to entering the for loop as
iter = zeros(31,1);
Y = zeros(31,1);
iter(1) = 1;
Y(1) = iter(1);
The same should be done for X as well.

MATLAB Function (Solving an Error)

I have one file with the following code:
function fx=ff(x)
fx=x;
I have another file with the following code:
function g = LaplaceTransform(s,N)
g = ff(x)*exp(-s*x);
a=0;
b=1;
If=0;
h=(b-a)/N;
If=If+g(a)*h/2+g(b)*h/2;
for i=1:(N-1)
If=If+g(a+h*i)*h;
end;
If
Whenever I run the second file, I get the following error:
Undefined function or variable 'x'.
What I am trying to do is integrate the function g between 0 and 1 using trapezoidal approximations. However, I am unsure how to deal with x and that is clearly causing problems as can be seen with the error.
Any help would be great. Thanks.
Looks like what you're trying to do is create a function in the variable g. That is, you want the first line to mean,
"Let g(x) be a function that is calculated like this: ff(x)*exp(-s*x)",
rather than
"calculate the value of ff(x)*exp(-s*x) and put the result in g".
Solution
You can create a subfunction for this
function result = g(x)
result = ff(x) * exp(-s * x);
end
Or you can create an anonymous function
g = #(x) ff(x) * exp(-s * x);
Then you can use g(a), g(b), etc to calculate what you want.
You can also use the TRAPZ function to perform trapezoidal numerical integration. Here is an example:
%# parameters
a = 0; b = 1;
N = 100; s = 1;
f = #(x) x;
%# integration
X = linspace(a,b,N);
Y = f(X).*exp(-s*X);
If = trapz(X,Y) %# value returned: 0.26423
%# plot
area(X,Y, 'FaceColor',[.5 .8 .9], 'EdgeColor','b', 'LineWidth',2)
grid on, set(gca, 'Layer','top', 'XLim',[a-0.5 b+0.5])
title('$\int_0^1 f(x) e^{-sx} \,dx$', 'Interpreter','latex', 'FontSize',14)
The error message here is about as self-explanatory as it gets. You aren't defining a variable called x, so when you reference it on the first line of your function, MATLAB doesn't know what to use. You need to either define it in the function before referencing it, pass it into the function, or define it somewhere further up the stack so that it will be accessible when you call LaplaceTransform.
Since you're trying to numerically integrate with respect to x, I'm guessing you want x to take on values evenly spaced on your domain [0,1]. You could accomplish this using e.g.
x = linspace(a,b,N);
EDIT: There are a couple of other problems here: first, when you define g, you need to use .* instead of * to multiply the elements in the arrays (by default MATLAB interprets multiplication as matrix multiplication). Second, your calls g(a) and g(b) are treating g as a function instead of as an array of function values. This is something that takes some getting used to in MATLAB; instead of g(a), you really want the first element of the vector g, which is given by g(1). Similarly, instead of g(b), you want the last element of g, which is given by g(length(g)) or g(end). If this doesn't make sense, I'd suggest looking at a basic MATLAB tutorial to get a handle on how vectors and functions are used.