Clear Filters
Clear Filters

Linking data points

3 views (last 30 days)
Yigit
Yigit on 22 Nov 2011
I know this is very basic but couldn't figure out how to.
I use this code to read data from my device;
clear all;
close all;
y = zeros(5000);
s1 = serial('/dev/ttyACM0');
s1.BaudRate=115200;
fopen(s1);
clear data;
for i= 1:20
data=fscanf(s1);
y(i) = str2double(data);
fit = polyfit(i, y(i), 1)
plot(fit,y(i))
title('Data Output');
xlabel('Points');
ylabel('Values');
drawnow;
hold on
if y(i) > 10
fprintf(s1, '1');
end
if y(i) < 10
fprintf(s1, '0');
end
end
fclose(s1);
And it works as expected. But it only shows points, not a plot. Not sure what is going on.

Answers (3)

Fangjun Jiang
Fangjun Jiang on 22 Nov 2011
The way you did, every time it just plots one point (fit,y(i)).
Pre-allocate two vectors before the for-loop
N=20;
y=zeros(N,1);
fit=zeros(N,1);
Inside the for-loop, change it to
fit(i)=polyfit(i, y(i), 1)
Move all the following out of the for-loop:
title('Data Output');
xlabel('Points');
ylabel('Values');
drawnow;
hold on
After the for-loop, run
plot(fit,y)

Yigit
Yigit on 22 Nov 2011
It gives an error ;
Code ;
clear all;
close all;
s1 = serial('/dev/ttyACM0');
s1.BaudRate=115200;
fopen(s1);
clear data;
N=20;
y=zeros(N,1);
fit=zeros(N,1);
for i= 1:20
data=fscanf(s1);
y(i) = str2double(data);
fit(i) = polyfit(i, y(i), 1);
title('Data Output');
xlabel('Points');
ylabel('Values');
drawnow;
hold on
if y(i) > 10
fprintf(s1, '1');
end
if y(i) < 10
fprintf(s1, '0');
end
end
plot(fit,y)
fclose(s1);
Error ;
Warning: Polynomial is not unique; degree >= number of data points.
> In polyfit at 71
In dataq at 23
??? In an assignment A(I) = B, the number of elements in B and
I must be the same.
Error in ==> dataq at 23
fit(i) = polyfit(i, y(i), 1);
  2 Comments
Fangjun Jiang
Fangjun Jiang on 22 Nov 2011
fit() is actually a function, can you try to change the variable name?
Yigit
Yigit on 22 Nov 2011
same behavior unfortunately.

Sign in to comment.


Walter Roberson
Walter Roberson on 22 Nov 2011
You would get that error if you encountered a line that had a non-number, including at end of file (which you are not testing for)
Is there a particular reason to use fscanf() and then str2double() what you get from that? If you were going to use str2double() I would expect fgets() or fgetl(); if you were going to use fscanf() I would expect a format specifier to be given to it that would do the conversion.
Note that str2double() only processes a single value per string, never a vector of values per string. Because of that, you are doing a polyfit() on at most 1 value. That is not going to be very productive.

Community Treasure Hunt

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

Start Hunting!