How do I sort data into two different variables?

6 views (last 30 days)
I have an arduino connected and it reads values from it. One is time and one is distance.
.
I think I would use the following:
data = sscanf('%i seconds')
data = sscanf('%f meters')
because the time data is an integer number and the distance data is has decimal numbers. However, I'm unsure how to utilise this properly. I'm trying to display these values into GUI edit text boxes so I need to be able sort these properly.
Would I use an if statement? I have tried
if a == sscanf('%i seconds')
a = x
else
a = y
end
but this isn't working.

Accepted Answer

Walter Roberson
Walter Roberson on 28 May 2015
If you are reading from the device, you need fscanf() not sscanf(), and you need to tell it which device to read from.
As a style matter, I do not recommend using %i for integers unless you need to deal with the possibility that the input might be written in octal or hex. For example, if the input is '0135' do you want that interpreted as 135 decimal, or do you want it interpreted as 93 decimal? The %i format would interpret it as 93 decimal. Use %d for items that must be decimal, and use %f for items that you would not be upset if the input was written in floating point form. For example, even if you expect an integer from the user, if the user writes '1E5' then %f format would know to interpret that as 100000.
In cases where there is any possibility of the input being invalid or not what you expected, such as if characters got dropped, or if you do not know which of several valid inputs you might be receiving, then it is safer to read the line as a string and then to examine what you got. For example you are trying
fscanf(s, '%d seconds')
and the device sends '17 meters' then the number might be parsed but then the 's' that you expect would not match the 'm' of the input. When that happens when you are reading from a serial device, the 'm' of the actual input would be "put back" into the stream, ready to be read by the next call to read data. And then your next call is going to fail because you are not going to be expecting to get a line starting with 'meters'. But if you instead used
L = fgetl(s);
then you can do several tests on L to find out what kind of data is in the line before you process it. For example,
while true
gottime = false;
gotdistance = false;
if strfind(L,'seconds')
t = sscanf(L, '%d');
gottime = true;
elseif strfind(L,'meters')
d = sscanf(L, '%f');
gotdistance = true;
else
fprintf('unexpected input line: |%s|\n', L);
continue
end
if gottime
.....
end
if gotdistance
.....
end
end

More Answers (0)

Categories

Find more on Tables 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!