MATLAB: I want to use Parfor with this code

parfor

hello , please i need to know how can i convert this code with parfor loop …
for Sensor_i = 1 : NumberOfSensors
if (SensorsTargetsCoverage(Sensor_i, SparseTargetIndex) >= ReliabilityThreshold)
CriticalSensorFlag(Sensor_i) = 1;
CriticalSensorCounter = CriticalSensorCounter + 1;
CriticalSensor(CriticalSensorCounter) = Sensor_i;
end;
end;
when i write parfor it show me the error message "valid indices are restricted in parfor loops"
Thanks

Best Answer

What do you expect if two parallel works process these lines at the same time:
CriticalSensorCounter = CriticalSensorCounter + 1;
CriticalSensor(CriticalSensorCounter) = Sensor_i;
? Which of the workers is allowed to increase and access CriticalSensorCounter at first? What happens, if the first worker increases this counter and the second increases it also before the first has used it?
Better collect the indices after the loop:
CriticalSensorFlag = zeros(1, NumberOfSensors);
parfor Sensor_i = 1 : NumberOfSensors
if SensorsTargetsCoverage(Sensor_i, SparseTargetIndex) >= ReliabilityThreshold
CriticalSensorFlag(Sensor_i) = 1;
end
end
CriticalSensorCounter = find(CriticalSensorFlag);