MATLAB: Error using vertcat – Dimensions of matrices being concatenated are not consistent

errorvertcat

a = -pi; b = pi; nx = 32;
x = linspace(a,b,nx+1);
dx = (b-a)/nx;
u = sin(x);
Du = cos(x);
cdu(2:nx) = central(u,dx);
cdu(1) = (4*u(2) - 3*u(1) - u(3))/2/dx;
cdu(nx+1) = (-4*u(nx) + 3*u(nx+1) + u(nx-1))/2/dx;
fdu(1:nx) = forward(u,dx);
fdu(nx+1) = cdu(nx+1);
bdu(2:nx+1) = backward(u,dx);
bdu(1) = cdu(1);
plot(x,Du,'r',x,fdu,'b',x,bdu,'g',x,cdu,'k');
axis([ a b min(Du) max(Du)]);
legend('Exact', 'Forward', 'Backward', 'Central');
xlabel('x'); ylabel('y');
title('Finite-difference approximations')
figure(2);
plot(x,Du-fdu,'b',x,Du-bdu,'g',x,Du-cdu','k');
legend('F. Error', 'B. Error', 'C. Error');
fprintf(' x Du fdu Du-fdu cdu Du-cdu bdu Du-bdu\n')
temp = [x;Du;fdu;Du-fdu;cdu;Du-cdu';bdu;Du-bdu];
fprintf('%9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f %9.4f\n', temp)
When I click "run" on my command windows appears:
Error using vertcat Dimensions of matrices being concatenated are not consistent
Error in Esempio293 (line 37) temp = [x;Du;fdu;Du-fdu;cdu;Du-cdu';bdu;Du-bdu];
What can I do?

Best Answer

You can use the debugger: Set a breakpoint in this line, run the code again, and when Matlab stops check the dimensions of the variables. The error message tells you, that they have a different number of columns.