How to combine function with other codes in one .m fine (Matlab)

136 Views Asked by At
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?

1

There are 1 best solutions below

0
On BEST ANSWER

Okay, so there is a few things wrong here. Firstly with your error:

Error: File: find_root.m Line: 11 Column: 14 Function with duplicate name "find_root" cannot be defined.

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 input x). Something else to watch out for is including e as a parameter for your function. If you do not include e as a function parameter in the definition function y = find_root(x,e) and the function handle fun = @(x)find_root(x,e);, then the e you defined earlier will be out of scope within the function. The following code worked just fine for me (saved as test.m):

%% Script
clear all
close all
clc

e = .25;
fun = @(x)find_root(x,e);
z = fzero(fun,1);
yy = z+.5^2*z/e-z^3/e;

%% Functions
function y = find_root(x,e)
    y1 = x+0.5^2*x/e-x^3/e;
    y = -e*x + e*y1 +.5^2*y1-y1^3;
end

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!