Converting FOR to PARFOR Code

2 views (last 30 days)
dsmalenb
dsmalenb on 28 Oct 2018
Commented: dsmalenb on 29 Oct 2018
Hello!
I am a bit confused about why I am having a particular error while converting a small and simple piece of my code form a FOR LOOP to a PARFOR LOOP. If someone could help me understand what I am missing I would be very thankful:
The original code is:
close all; clear all; clc;
slots = 3;
OutputV = '';
for j=1:2^slots
if rand < 0.5
strng = '0';
else
strng = '1';
end
OutputV = strcat(OutputV,strng);
end
OutputV = fliplr(OutputV);
Av = sym('a',[1,2^slots]); % We require 2^slots variables
Eq = sym('eq',[1,2^slots]); % We require 2^slots equations
for ctr = 0:2^slots-1
ctr
S = dec2bin(ctr,4);
S = fliplr(S); % Matlab reads from left to right so flip.
A = strfind(S,'1');
N = numel(A);
L = length(S);
Eq(1+ctr) = 0;
for j=1:N
B = combnk(A,j);
coeff = sum(2.^(B-1),2);
for k=1:numel(coeff)
Eq(1+ctr) = Eq(1+ctr) + Av(1,coeff(k)+1);
end
end
% Need to substract constant term & output value
Eq(1+ctr) = Eq(1+ctr) - Av(1,1) - OutputV(1+ctr);
end
The modified code is:
close all; clear all; clc;
slots = 5;
OutputV = '';
for j=1:2^slots
if rand < 0.5
strng = '0';
else
strng = '1';
end
OutputV = strcat(OutputV,strng);
end
OutputV = fliplr(OutputV);
Av = sym('a',[1,2^slots]); % We require 2^slots variables
Eq = sym('eq',[1,2^slots]); % We require 2^slots equations
% Conver to parfor
parfor ctr = 0:2^slots-1
S{1+ctr} = dec2bin(ctr,4);
S{1+ctr} = fliplr(S{1+ctr});
A{1+ctr} = strfind(S{1+ctr},'1');
N{1+ctr} = numel(A{1+ctr});
L{1+ctr} = length(S{1+ctr});
Eq{1+ctr} = 0;
for j = 1:N{1+ctr}
B{1+ctr} = combnk(A{1+ctr},j); % < --- Error here or
coeff{1+ctr} = sum(2.^(B{1+ctr}-1),2); % < --- Error here?
% for k=1:numel(coeff{1+ctr})
% Eq{1+ctr} = Eq{1+ctr} + Av(1,coeff(k)+1);
% end
end
% Need to substract constant term & output value
% Eq(1+ctr) = Eq(1+ctr) - Av(1,1) - OutputV(1+ctr);
end
The error I get is: Error using LinearP3Parallel1>(parfor supply) An UndefinedFunction error was thrown on the workers for 'B'. This might be because the file containing 'B' is not accessible on the workers. Use addAttachedFiles(pool, files) to specify the required files to be attached. See the documentation for 'parallel.Pool/addAttachedFiles' for more details. Error in LinearP3Parallel1 (line 22) parfor ctr = 0:2^slots-1 Caused by: Undefined function 'B' for input arguments of type 'double'

Accepted Answer

Walter Roberson
Walter Roberson on 29 Oct 2018
Initialize B as a cell array of appropriate size before the parfor.
Someone else came across the same problem about a week ago.
  1 Comment
dsmalenb
dsmalenb on 29 Oct 2018
Thank you. I knew it was something stupid.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!