Error using vertcat Dimensions of arrays being concatenated are not consistent.

조회 수: 2 (최근 30일)
Hi,
I'm trying to read mpu6050 and emg data from serial port simultaneously via esp32. But it gives and error '' Error using vertcat ,dimensions of arrays being concatenated are not consistent.'' Matlab sometimes gives 4 , sometimes 3 datas and it interrupts the code. How can i make sure that 4 datas read from serial port ?
Any ideas??
a=serial('COM3','BaudRate',115200);
fopen(a);
D=zeros(1000,4);
for t=1:1000
data = fscanf(a,'%d');
D = [D;data'];
D = D(2:end,:);
plot(D);
pause(0.1)
end

채택된 답변

Guillaume
Guillaume 2019년 3월 24일
"How can i make sure that 4 datas read from serial port ?"
Specify the number of elements to read as the 3rd argument of fscanf:
data = fscanf(a, '%d', 4);
However, as noted at the bottom of the documentation of fscanf, the read can also complete before 4 elements are read (e.g. because of a timeout), so always check afterward that you've actually read 4 elements:
if numel(data) != 4
%do something
end
Also
D = zeros(1000, 4);
for t = 1:1000
%... does not matter
D = [D; data];
D = D(2:end, :);
%... does not matter
end
doesn't make sense. You create D as a 1000x4 array full of zeros. In your loop, instead of filling that array, for each step you then add a row below your original array, and remove the top row (so you still end up with 1000 rows). The whole point of creating a 1000x4 array is to preallocate the memory to avoid array resizing which is slow. You made it even worse with your code. Instead of one resize per step, you have 2 resize. Twice as slow.
The proper way
D = zeros(1000, 4);
for t = 1:size(D, 1) %note that I use size instead of a hardcoded values. If you want to read 2000 values, you now only need to change the zeros call
%does not matter
D(t, :) = data; %store in the preallocated array
end
  댓글 수: 1
Kadir Tolga Dogukanli
Kadir Tolga Dogukanli 2019년 3월 25일
thank you, it worked for me!!! But I have one more problem , plotting is very slow . I want it to be real time. do you have any idea?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB Support Package for Arduino Hardware에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by