MATLAB parfor报错‘Variable in a parfor cannot be classified’求助
Hey there, let's break down why you're hitting this error and how to fix it. That The variable A in a parfor cannot be classified message comes up because MATLAB's parfor can't figure out how your nested loops are accessing the 3D array A—the conditional check on Lesion_Visible makes the indexing unpredictable, and parfor needs strict rules to ensure each parallel iteration doesn't interfere with others.
Here's a straightforward fix:
Instead of nesting three loops inside parfor, we'll first identify all the positions in A that actually need calculation, then iterate over those positions using linear indices. This makes the array access pattern crystal clear for parfor.
r = 5; Mu = 12.57e-9; Nu = 12e6; I = 1.8; const = pi*Nu*Mu*r*I; a = 55; b = 69; c = 206; [m,n,p] = size(Lesion_Visible); A = zeros(m,n,p); % First, get all linear indices where we need to compute values target_indices = find(Lesion_Visible ~= 0); total_targets = numel(target_indices); % Let MATLAB manage the parpool automatically instead of manual parpool(2) parfor idx = 1:total_targets % Convert linear index back to 3D coordinates [J,I,K] = ind2sub([m,n,p], target_indices(idx)); Theta = atand((J-b)/(I-a)); Rho = abs((I-a)/cosd(Theta))*0.05; Z = abs(c-K)*0.05; syms k E = vpa(const*int(abs(besselj(0,Rho*k)*exp(-Z*k)*besselj(0,r*k)),0,20),5); A(target_indices(idx)) = E; end % Clean up the parallel pool when done delete(gcp('nocreate'))
Why this works:
- By precomputing
target_indices, we eliminate the conditional check inside the parfor loop. Each iteration ofidxhandles exactly one unique position inA, so parfor can easily verify that no two iterations are writing to the same spot. - Linear indexing bypasses the ambiguity of nested 3D indexing that was confusing parfor's classification system.
A bonus speed tip:
Your current code uses symbolic integration (syms k + vpa), which is inherently slow—even with parfor, the overhead of symbolic math might eat up most of your parallel gains. If you can switch to numerical integration, you'll see a massive speed boost. Here's how to adjust that part:
% Replace the symbolic integral with numerical integration parfor idx = 1:total_targets [J,I,K] = ind2sub([m,n,p], target_indices(idx)); Theta = atand((J-b)/(I-a)); Rho = abs((I-a)/cosd(Theta))*0.05; Z = abs(c-K)*0.05; % Define a numerical function handle for integration integral_func = @(k) abs(besselj(0,Rho*k).*exp(-Z*k).*besselj(0,r*k)); integral_result = integral(integral_func, 0, 20); A(target_indices(idx)) = const * integral_result; end
This version skips symbolic variables entirely, uses MATLAB's optimized integral function, and plays much nicer with parallel execution.
内容的提问来源于stack exchange,提问作者Luis Lira

