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

1 view (last 30 days)
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??
for t=1:1000
data = fscanf(a,'%d');
D = [D;data'];
D = D(2:end,:);

Accepted Answer

Guillaume on 24 Mar 2019
"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
D = zeros(1000, 4);
for t = 1:1000
%... does not matter
D = [D; data];
D = D(2:end, :);
%... does not matter
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
  1 Comment
Kadir Tolga Dogukanli
Kadir Tolga Dogukanli on 25 Mar 2019
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?

Sign in to comment.

More Answers (0)


Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!