Error: The variable in a parfor cannot be classified.

6 次查看(过去 30 天)
I am trying to convert my code over to run with parfor, since as it is it takes a long time to run on its own. However I keep getting this error. I have search around on the website and have read people with similar problems, but none of those answers seem to fix my problem. My code is as follows. dArea is the variable that seems to be giving me the issue. It is preallocated.
parfor i=1:500
data = regionprops(cc, 'Area');
Area=[data.Area];
Number(i)=length(Area);
for j=1:length(Area)
dArea(i,j)=Area(1,j);
end
end
  2 个评论
Walter Roberson
Walter Roberson 2015-6-10
As an experiment, what happens with
parfor i = 1 : 500
data = regionprops(cc, 'Area');
Area = [data.Area];
len = length(Area);
Number(i) = len;
dArea(i,1:len) = Area(1:len);
end
Edric Ellis
Edric Ellis 2015-6-11
Performing a single assignment like this is definitely preferable. Unfortunately, in the form as you have it, dArea still cannot be classified because it doesn't follow the "slicing" rules - instead of indexing with 1:len, the second subscript must be simply :. There's more about the slicing rules here: http://www.mathworks.com/help/distcomp/sliced-variables.html

请先登录,再进行评论。

回答(1 个)

Edric Ellis
Edric Ellis 2015-6-11
An equivalent problem is the following:
parfor i=1:5
data = rand(5, 1);
for j = 1:numel(data)
out(i, j) = data(j);
end
end
The problem is the loop bounds on the inner for loop. As described in the documentation, a nested for loop must use constant bounds. So, you could fix the example above like so:
n = 5;
parfor i=1:n
data = rand(n, 1);
for j = 1:n % loop bound is now a known constant value
out(i, j) = data(j);
end
end
However, as Walter suggests, it's better still to do this:
n = 5;
parfor i=1:n
data = rand(n, 1);
out(i, :) = data;
end
to avoid having a simple assignment loop.
  3 个评论
Nathan
Nathan 2015-6-11
The problem with using
out(i, :) = data;
Is that the size of data changes with every iteration. I have out preallocated as a large matrix, but the reason I use the loop to assign each value is because using the code as you wrote it gives me a dimension mismatch error. Unless there is a way to assign a value to another matrix of a different size I think I have to use a loop. Example
x=zeros(10,6);
parfor i=1:10
y=rand(1,randi([0 5]));
x(i,:)=y
end
Walter Roberson
Walter Roberson 2015-6-11
The tArea I showed creates a temporary vector of the maximum length, of all 0, write the data into it, and then write the vector as a column.
The code you have as a loop does not write into some locations so the result depends on how you initialize it which makes it both input and output. The temporary vector of 0 gives definite value to all locations and makes it output only.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by