Vector Error
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
David Young
le 25 Jan 2012
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 commentaire
Walter Roberson
le 25 Jan 2012
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)
Voir également
Catégories
En savoir plus sur Testing Frameworks dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!