Vector Error
조회 수: 1 (최근 30일)
이전 댓글 표시
I am trying to read data from a serial port and store the values in a vector to eventually plot.
I keep getting the following error:
"In an assignment A(I) = B, the number of elements in B and I must be the same."
I understand that the data from the serial port may not be the same size, but I cannot figure out how to remedy this problem. Here is the basic program that I am testing with:
for i = 1 : 10
y(i) = fread(s)
end
I am also just using Hyperterminal to test.
Any help is much appreciated!
댓글 수: 0
답변 (2개)
David Young
2012년 1월 25일
A call to fread returns a vector, but you can only store a single number in y(i) if i is a scalar (which it is in your code - i is one of the numbers from 1 to 10).
The solution really depends on what you want to do with the data afterwards, but one possibility is to store each vector in one element of a cell array. To do this, you'd replace the second line of your code with
y{i} = fread(s);
(You could also preallocate y before the loop, using
y = cell(1, 10);
)
This keeps the data from each call to fread separate.
If you want to combine the vectors into one big vector, you can do
y = [];
for i = 1:10
y = [y; fread(s)];
end
You may well need to make your code more complex in order to read successfully from the serial port - for example, you may need to test BytesAvailable(s) to see whether to continue the loop or pause.
댓글 수: 1
Walter Roberson
2012년 1월 25일
Note: fread() applied to a serial port will read until the end of the defined InputBufferSize unless it gets an error or timeout.
If you want to read only 1 byte, specify the size
fread(s,1)
참고 항목
카테고리
Help Center 및 File Exchange에서 Testing Frameworks에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!