In an assignment A(I) = B, the number of elements in B and I must be the same? While Loop

1 view (last 30 days)
Hello! I am connecting an arduino sensor to Matlab to store the data being read from a sensor. The sensor has a proximity sensor attatched to it so that the sensor only reads data when something is in front of it. My problem is when I try to read all the values generated from the loop it gives me the error when nothing is in front of the sensor( nothing is being read): In an assignment A(I) = B, the number of elements in B and I must be the same.
However when I do not try to save every value, the code works fine when something is and is not in front of the sensor.
Code that does not store every iteration value generated in loop but works when something is and is not in front of data:
%e
s = serial('COM3');
set(s,'BaudRate',9600);
fopen(s);
out=[];
while 1
value = fscanf(s);
out(length(out) + 1) = str2num(value);
disp(out);
end
fclose(s)
Code that stores every iteration when something placed in front of sensor but gives me above error if nothing is in front of sensor:
s = serial('COM3');
set(s,'BaudRate',9600);
fopen(s);
out=[];
for i=1:60
value = fscanf(s);
out(length(out) + 1) = str2num(value);
disp(out);
end
fclose(s);
^ I've also tried doing while 1 instead of for i=1:60 but it still does not work
Please help I really do appreciate it! Thank you!

Accepted Answer

Geoff Hayes
Geoff Hayes on 13 Nov 2014
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
value = '123a';
then the
str2num(value)
ans =
[]
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.

More Answers (0)

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!