clear all;
close all
clc
e = .25;
%fun = @find_root;
z = fzero(fun,1)
yy = z+.5^2*z/e-z^3/e
%=================================
function y = find_root(x)
y1 = x+0.5^2*x/e-x^3/e;
y = -e*x + e*y1 +.5^2*y1-y1^3
end
It can work if I separate two parts in different .m file of the above code. However, when I combine them together, Matlab shows:
Error: File: find_root.m Line: 11 Column: 14 Function with duplicate name "find_root" cannot be defined.
Since I want to set e from 0 to 1 in for loop and I cannot add parameter in the following way
z = fzero(fun(x,e),1)
that is why I have to combine both parts in ONE .m file.
How to fix it?
Okay, so there is a few things wrong here. Firstly with your error:
This is caused when you give your file the same name as a function contained in the script. I suggest you change it to something else (e.g.
calc_yy.m). Other than that you should define your function as a function handle with your desired input (fun = @(x)find_root(x,e);is a function handle with inputx). Something else to watch out for is includingeas a parameter for your function. If you do not includeeas a function parameter in the definitionfunction y = find_root(x,e)and the function handlefun = @(x)find_root(x,e);, then theeyou defined earlier will be out of scope within the function. The following code worked just fine for me (saved astest.m):Good luck with your future MATLAB endeavours and don't ever feel silly for mistakes like this, we have all made them at some point!