2016-08-11 54 views
1

我希望用parfor嵌套的循環,我已經做出了表率顯示我的結構:分類錯誤通過移位索引解決,爲什麼?

temp_vars = 1:10; 
global_arr = zeros(10,10); 

parfor i=0:9 
    for j=0:9 
     constant_var = temp_vars(i+1); 
     global_arr(i+1, j+1) = i*j*constant_var; 
    end 
end 

MATLAB給我的錯誤:Error: The variable global_arr in a parfor cannot be classified.

但是,如果我將ij的值更改爲1..10而不是0..9,那麼它會很神奇地運行良好。這是爲什麼?

回答

1

問題是,您使用相對索引而不是絕對索引(即i+1而不是i)引用global_arr。當您使用平行for時,每個「切片」的global_arr獨立計算在其循環中的位置,相對指數意味着依賴位置,這是禁止的。

試試這個:

parfor i = 1:10; 
    for j = 1:10; 
     constant_var = temp_vars(i); 
     global_arr(i, j) = (i-1)*(j-1)*constant_var; 
    end 
end 

更確切地說,只有parfor循環中的第一個索引可以取決於循環迭代,所有的人都被視爲常數。所以,你可以在一個相對的方式使用i,但不j

parfor i = 0:9; 
    for j = 1:10; 
     constant_var = temp_vars(i+1); 
     global_arr(i+1,j) = i*(j-1)*constant_var; 
    end 
end 

From MATLAB doc

When you use other variables along with the loop variable to index an array, you cannot set these variables inside the loop. In effect, such variables are constant over the execution of the entire parfor statement. You cannot combine the loop variable with itself to form an index expression.

+0

說我變'temp_vars'是更長的時間,我需要使用更復雜的indicices不能得到解決通過簡單地從「0..9」轉換到「1..10」,例如'constant_var = temp_vars(10 + 100 * j + 200 * i);'。這是否意味着我不能使用parfor? – BillyJean

+1

你可以使用它,但是在循環之前將'temp_vars'的索引列表作爲'i'和'j'的函數,然後對它們進行絕對引用。像循環外的'temp_vars_ind(i,j)= 10 + 100 * j + 200 * i',然後是循環中的'temp_vars(temp_vars_ind(i,j))'。 – EBH

+0

這是一個好的解決方案,可選擇地使一個自治函數爲'ind = @(i,j)10 + 100 * j + 200 * i',然後調用'temp_vars(ind(i,j))'? – BillyJean