Linking data points
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(3 个)
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)
0 个评论
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.
0 个评论
另请参阅
类别
在 Help Center 和 File 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!