MATLAB Language Watch out for array size changes


Some common operations in MATLAB, like differentiation or integration, output results that have a different amount of elements than the input data has. This fact can easily be overlooked, which would usually cause errors like Matrix dimensions must agree. Consider the following example:

t = 0:0.1:10;        % Declaring a time vector
y = sin(t);          % Declaring a function

dy_dt = diff(y);     % calculates dy/dt for y = sin(t)

Let's say we want to plot these results. We take a look at the array sizes and see:

size(y) is 1x101
size(t) is 1x101


size(dy_dt) is 1x100

The array is one element shorter!

Now imagine you have measurement data of positions over time and want to calculate jerk(t), you will get an array 3 elements less than the time array (because the jerk is the position differentiated 3 times).

vel = diff(y);       % calculates velocity vel=dy/dt for y = sin(t)  size(vel)=1x100
acc = diff(vel);     % calculates acceleration acc=d(vel)/dt         size(acc)=1x99
jerk = diff(acc);    % calculates jerk jerk=d(acc)/dt                size(jerk)=1x98   

And then operations like:

x = jerk .* t;          % multiplies jerk and t element wise

return errors, because the matrix dimensions do not agree.

To calculate operations like above you have to adjust the bigger array size to fit the smaller one. You could also run a regression (polyfit) with your data to get a polynomial for your data.

Dimension Mismatch Errors

Dimension mismatch errors typically appear when:

  • Not paying attention to the shape of returned variables from function/method calls. In many inbuilt MATLAB functions, matrices are converted into vectors to speed up the calculations, and the returned variable might still be a vector rather than the matrix we expected. This is also a common scenario when logical masking is involved.
  • Using incompatible array sizes while invoking implicit array expansion.