Nancy - if nothing is in front of the sensor, then (as you say) nothing is being read. So you need to guard against the case when this happens because the failure is (probably) occurring when value is an empty string, and the str2num(value) becomes an empty matrix which you try to assign to your vector out - so the code is trying to assign zero elements to one element, and so the error makes sense.
Try the following
out=[];
for i=1:60
[value,count] = fscanf(s);
if count>0
out(length(out) + 1) = str2num(value);
end
disp(out);
end
where we use the number of values read, count, to determine if we have any data to add to out. An alternative would be the following condition
[value,count] = fscanf(s);
if ~isempty(value)
out(length(out) + 1) = str2num(value);
end
So if our value string is non-empty, then convert it to a number and add it to out. If you are only ever reading in numbers or nothing, then the above will be fine. But if for some reason your value is
then the
returns an empty matrix too which will generate an error. And so it may be safer to do
out=[];
for i=1:60
[value,count] = fscanf(s);
if count>0
valueAsNum = str2um(value);
if ~isempty(valueAsNum)
out = [out ; valueAsNum];
end
end
disp(out);
end
Note the alternative for updating the out vector.
Best Answer