필터 지우기
필터 지우기

Linking data points

조회 수: 3 (최근 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에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by