Incorrect results from parfor

hi, thanks in advance for your help. i am constructing a function which contains a parfor loop, which i am unfamiliar with. Although it runs, the results are incorrect; if i replace the 'parfor' with 'for' (nothing else changed), then the results are correct, with much longer running time. fun_wn and fun_idf_HS are two user-defined functions. The new function just prints out their values when i and j satisfies certain condition. (symptom: x and y_sp{j} are printed out correctly, but feval(fun_1,x,y_sp{j}) and feval(fun_2,y_sp{j}) are not.) thanks a looot!
function output = fun_wn_HS4(x)
global d_HS4_o prescore_HS4 vocabulary_HS4
fun_1 = @fun_wn;
fun_2 = @fun_idf_HS;
output = zeros(size(d_HS4_o,1),1);
parfor i=1:size(d_HS4_o,1)
y_sp = strtrim(strsplit(d_HS4_o{i},' '));
for j=1:length(y_sp)
if i==506 && j==13
x
y_sp{j}
feval(fun_1,x,y_sp{j})
feval(fun_2,y_sp{j})
end
end
end
end

Answers (1)

Unless the user is passing function names to you, use
fun_1(x,y_sp{j});
fun_2{y_sp{j});
instead of using feval()

5 Comments

thanks a lot! But i have tried using the function directly like
fun_1(x,y_sp{j});
fun_2{y_sp{j});
the results are still incorrect. in particular, the result fun_1(x,y_sp{j}) does not return the correct functional value within the parfor loop. (it does report the correct functional value if i replace the parfor with for...
What value does it return and what value are you expecting?
Do fun_1 or fun_2 have "side effects" -- that is, do they make changes to any variable that is input to the calculations? For example you show a "global" but you do not show the variables being used: if fun_1 or fun_2 are reading the globals and modifying them, then you are going to run into problems with order of execution.
Anthony
Anthony on 7 Jan 2014
Edited: Anthony on 7 Jan 2014
thanks. although there is no problem with the inputs, x and y_sp{j}, the function always returns zero when i use parfor, which is not correct.
if i run fun_1 directly in the command window with the same input values, or i replace parfor with for, then the result will be the same value, strictly positive number, which is the correct one.
regarding globals, they are calling the same set of global variables, and i do not change/modify any global variable within a function. (in fact, there is no change to the global variables at all, which are just some source data previously generated.)
GLOBAL data is not automatically transferred from the MATLAB client to the workers running the body of the PARFOR loop. So, you either need to do this manually, or ideally you'd re-work the functions to rely on explicit input arguments.
i see... will try, thanks a lot!

Sign in to comment.

Categories

Asked:

on 6 Jan 2014

Commented:

on 9 Jan 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!