Vector Error

2 次查看(过去 30 天)
Steve
Steve 2012-1-25
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!

回答(2 个)

David Young
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
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)

请先登录,再进行评论。


Steve
Steve 2012-1-25
Awesome. Thanks guys!!

Community Treasure Hunt

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

Start Hunting!

Translated by