
How can i scan data and store it in an array?
4 次查看(过去 30 天)
显示 更早的评论
code: clear all clc arduino=serial('COM19','BAUDRATE',9600);
fopen(arduino);
y = zeros(1,10);
for i=1:10
y(i) = fscanf(arduino,'%d');
end
disp(y);
fclose(arduino);
the error I am getting is: In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in plotpl (line 7) y(i) = fscanf(arduino,'%d');
so how can I store the scanned value in an array?
0 个评论
回答(1 个)
Rajanya
2025-1-28
The reason for this error is mostly because the left and right side of the below assignment has different number of elements.
y(i) = fscanf(arduino,'%d');
If the scanned value is an array containing 10 elements as I assume, instead of using a loop that accesses only a single index of 'y' and attempts to assign the entire array to that single index, you can declare 'y' as an array of 10 elements and directly assign the scanned array to y.
For example, refer to the demo example given below:

Here also, we get the same error since we are trying to assign a vector 'v' to a single element. Taking care of the types and sizes of the left hand and right hand operands during an assignment will avoid all such errors.
You can also have a look at a similar question here - https://www.mathworks.com/matlabcentral/answers/158915-in-an-assignment-a-i-b-the-number-of-elements-in-b-and-i-must-be-the-same
Thanks, hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!