Matlab parfor循环调用自定义函数遇UndefinedFunction错误求助
parfor and Custom Functions in MATLAB Ah, I’ve hit this exact snag before when using parfor with custom MATLAB functions—those parallel workers run in their own little isolated workspaces, so they don’t automatically pick up the function files your main session uses. Let’s walk through what’s going wrong and how to fix it.
What’s Causing the Error?
The error tells us the workers can’t find wph (quick note: your code uses wph1, so double-check for a typo here first—either in your code or the function filename!). When you spin up a parallel pool, each worker doesn’t inherit the function definitions or path settings from your main MATLAB environment. You have to explicitly share the files they need to run your code.
Step-by-Step Solutions
1. Attach the Function File to Your Parallel Pool
The most straightforward fix is to send your wph1.m file to all workers before running the parfor loop. Here’s how:
- First, make sure you have an active parallel pool (if not, MATLAB will start one automatically, but we can handle it explicitly):
% Check if a pool exists; start one if it doesn't if isempty(gcp('nocreate')) parpool; end - Then attach your custom function file to the pool using
addAttachedFiles:addAttachedFiles(gcp, 'wph1.m'); - If your
wph1function depends on other files, you can attach multiple files at once with a cell array:addAttachedFiles(gcp, {'wph1.m', 'helper_function.m'});
2. Add the Function’s Directory to the Workers’ Path
If you have a whole folder of custom functions, you can instead add that directory to the MATLAB path on every worker. Use an spmd block to run this setup once across all workers:
spmd % Replace with the full path to your function's directory addpath('C:\Your_MATLAB_Folder\Custom_Functions'); end
This makes all files in that directory accessible to the workers for the life of the parallel pool.
3. Double-Check for Typos
Don’t overlook the simplest fix! Your error mentions wph but your code calls wph1. Make sure:
- Your function file is named exactly
wph1.m(MATLAB is case-sensitive on some systems) - The call in your
parforloop matches the function name perfectly
Fixed Code Example
Here’s your original code with the parallel pool setup and file attachment added:
% Set up parallel environment and attach required function if isempty(gcp('nocreate')) parpool; end addAttachedFiles(gcp, 'wph1.m'); parfor i=1:10 k1=0.30+(0.35/20)*i; AX(i)=k1; for j=1:10 k2=0.5+(.35/20)*j; AY(i,j)=k2; wph(i,j)=wph1(k1,k2); % Confirm this matches your function name! end end
内容的提问来源于stack exchange,提问作者Vaswati Biswas

