Linking data points

1 次查看(过去 30 天)
Yigit
Yigit 2011-11-22
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.

回答(3 个)

Fangjun Jiang
Fangjun Jiang 2011-11-22
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 2011-11-22
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 个评论
Fangjun Jiang
Fangjun Jiang 2011-11-22
fit() is actually a function, can you try to change the variable name?
Yigit
Yigit 2011-11-22
same behavior unfortunately.

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2011-11-22
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.

类别

Help CenterFile Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by