Matlab报错求助:Undefined function 'myfun' for input arguments of type 'double'
Hey there, I feel your pain—those "undefined function" errors can be so frustrating when you swear you’ve got everything in place. Let’s walk through the most common fixes for this issue, step by step:
Double-check your function file’s name and syntax
Matlab is case-sensitive, so make sure your file is exactly namedmyfun.m(no capital letters, no extra characters). Open the file and verify the first line matches the required format for fsolve:function F = myfun(x) % Replace this with your actual system of equations F = [x(1)^2 + x(2)^2 - 4; x(1) - x(2) - 1]; endEnsure you have a closing
endstatement, the outputFis a column vector, and there are no typos in variable names or operators.Confirm Matlab’s working directory matches your file location
Even if you savedmyfun.malongside your other scripts, Matlab might not be looking in that folder. Runpwdin the command window to see your current working directory, thendirto check ifmyfun.mshows up. If it doesn’t:- Use
cd /path/to/your/folderto switch to the correct directory, or - Right-click the folder in Matlab’s file browser and select Add to Path → Selected Folders and Subfolders
- Use
Make sure your function isn’t being "hidden"
Sometimes a variable or another script with the same name can override your function. Runwhich myfunin the command window:- If the output points to a variable (not a
.mfile), runclear myfunto delete the variable and try again. - If it points to a different
.mfile (unlikely formyfun, but possible), rename your function to something unique likemy_nonlinear_system.mand update your fsolve call accordingly.
- If the output points to a variable (not a
Test your function directly before using fsolve
Skip fsolve for a minute and call your function manually with a test input, e.g.,myfun([1; 1]). If this throws an error, the problem is in your function’s code—not in fsolve. Fix those syntax or logic issues first, then go back to fsolve.Verify your fsolve call syntax
Ensure you’re passing the function handle correctly with the@symbol. A valid call should look like this:x0 = [0; 0]; % Initial guess for your variables x_solution = fsolve(@myfun, x0);Avoid using string inputs like
fsolve('myfun', x0)—while old Matlab versions supported this, function handles are more reliable and less prone to path-related issues.
These steps should cover 99% of cases where this error pops up. Chances are it’s a tiny oversight (like a capital letter in the filename or a missing end) that’s easy to miss after 3 hours of troubleshooting!
内容的提问来源于stack exchange,提问作者Parseval

