分类错误通过移动索引解决,为什么?
classification-error resolved by shifting index, why?
我希望将 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.
.
但是,如果我将 i
和 j
的值更改为 1..10
而不是 0..9
,那么它会神奇地运行良好。这是为什么?
问题是您引用 global_arr
使用相对索引而不是绝对索引(即 i+1
而不是 i
)。当您使用并行 for
时,global_arr
的每个 'slice' 都是根据其在循环中的位置独立计算的,并且相对索引表示从属位置,这是被禁止的。
试试这个:
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
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.
我希望将 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.
.
但是,如果我将 i
和 j
的值更改为 1..10
而不是 0..9
,那么它会神奇地运行良好。这是为什么?
问题是您引用 global_arr
使用相对索引而不是绝对索引(即 i+1
而不是 i
)。当您使用并行 for
时,global_arr
的每个 'slice' 都是根据其在循环中的位置独立计算的,并且相对索引表示从属位置,这是被禁止的。
试试这个:
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
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.