Vector Error

1 回表示 (過去 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!!

カテゴリ

Help Center および File ExchangeTesting Frameworks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by