valid indices are restricted in parfor loops when iterate every 2 elements
조회 수: 2 (최근 30일)
이전 댓글 표시
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];
댓글 수: 0
답변 (1개)
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
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
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 Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!