parfor with Matlab “the variable __ in a parfor ca

2019-03-06 14:15发布

So I am trying to call this function using a parfor (basically curve fitting using Fourier series through a vector in a parfor loop):

function[coefnames,coef] = fourier_regression(vect_waves,n)

    coef = zeros(length(vect_waves)-n,18);
    current_coef = zeros(18,1); % All the terms of the fourier series
    x = 1:n;

    parpool_obj = parpool;
    parfor i=n:length(vect_waves)

        take_fourier = vect_waves(i-n+1:i);

        f = fit(x,take_fourier,'fourier8');
        current_coef = coeffvalues(f);
        coef(i,1:length(current_coef)) = current_coef;

    end
    coefnames = coeffnames(f);

    delete(parpool_obj);
end

But I am just getting the error

"The variable coef in a parfor cannot be classified. See Parallel for Loops in MATLAB, "Overview".

I can't seem to find the solution anywhere, I don't know what the problem is. What's going on?

2条回答
萌系小妹纸
2楼-- · 2019-03-06 14:39

@Andras Deak put this in a comment, but the fix here is really simple - all you need to do is use a form of indexing for the second subscript to coef that is allowed by parfor. In this case, you need to do:

parfor i = ...
    coef(i, :) = ...;
end
查看更多
不美不萌又怎样
3楼-- · 2019-03-06 14:52

You are trying to fill an array before the amount of elements to be filled is known. What that means is that your loop has a different length of current_coef, which cannot be determined before the loop is run. You need to define everything before the parallel loop executes, because the order of execution is not predetermined.

The way to solve this is given by @AndrasDeak in the comments on this post. (I did not know the function, or that it always output the same number of elements, hence I could only give an explanation as to why this code does not work, but not the solution)

In general it is best to first optimise your code in terms of speed, then try and go parallel. Even without regression. Parallel processing is not some magic want you wave over sloppy code to magically make it execute faster, it is a highly optimised tool which works best on optimised codes.

For a better overview of parfor see Saving time and memory using parfor in Matlab?

Note you called this piece of code a "regression" in one of your earlier posts today, which it is not. If it were regression, however, parfor would not work.

查看更多
登录 后发表回答