フィルターのクリア

valid indices are restricted in parfor loops when iterate every 2 elements

2 ビュー (過去 30 日間)
Hamed Bolandi
Hamed Bolandi 2022 年 2 月 13 日
コメント済み: Walter Roberson 2022 年 2 月 14 日
I want to take the max and min of some random matricies every 2 iterations with parfor loop but got the error below:
"valid indices for min1 are restricted in parfor loops"
clc;
clear;
n= 100;
max1 = zeros(1,n);
min1 = zeros(1,n);
intrpVMStress1=0;
iValues = 1:2:n;
parfor idx = 1:numel(iValues)
i= iValues(idx)
x = randi(100,60,60,10);
x_max = max(x(:));
x_min = min(x(:));
max1(i) = x_max;
min1(i) = x_min;
end
max_all_samples = max(max1(:));
min_all_samples = min(min1(:));
max_min_all_samples = [max_all_samples,min_all_samples];

回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 2 月 13 日
max1(2*idx-1) = x_max;
min1(2*idx-1) = x_min;
and do not use iValue
parfor does want to see computations like that as direct text. You cannot use pre-computed indices. The reason for this is that with the direct text being hardcoded each time, it can do static bounds checks, whereas if you you used computed indices stored in a variable, then it would need to do tracing through all the control levels to prove that the value is always in range and cannot overlap with a different worker.
  3 件のコメント
Walter Roberson
Walter Roberson 2022 年 2 月 14 日
n= 100;
max1 = zeros(1,n);
min1 = zeros(1,n);
intrpVMStress1=0;
maxidx = floor(n/2);
parfor idx = 1 : maxidx
i = 2*idx - 1; %now you have i as well as idx
x = randi(100,60,60,10);
x_max = max(x(:));
x_min = min(x(:));
max1(2*idx-1) = x_max;
min1(2*idx-1) = x_min;
end
max_all_samples = max(max1(:));
min_all_samples = min(min1(:));
max_min_all_samples = [max_all_samples,min_all_samples];
Your original code cannot have iterated over i, as your i is only defined inside your loop.
If your original code had some other code that needed i then go ahead and do whatever it is outside the loop. For example,
n= 100;
max1 = zeros(1,n);
min1 = zeros(1,n);
intrpVMStress1=0;
maxidx = floor(n/2);
for i = 1 : 2 : n
filename = sprintf('data_%003d.txt', i);
if ~exists(filename, 'file')
errror('needed file does not exist: "%s"', filename);
end
end
parfor idx = 1 : maxidx
i = 2*idx - 1;
x = randi(100,60,60,10);
x_max = max(x(:));
x_min = min(x(:));
max1(2*idx-1) = x_max;
min1(2*idx-1) = x_min;
end
max_all_samples = max(max1(:));
min_all_samples = min(min1(:));
max_min_all_samples = [max_all_samples,min_all_samples];
Walter Roberson
Walter Roberson 2022 年 2 月 14 日
Note that you initialize min1 to all zero, and you only write in half of the entries, but you min() over all of the entries. You would therefore be taking min() over all of the entries including those zeros. Are you sure that is what you want to do?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by