MATLAB: How to solve this error ? Error using horzcat Dimensions of matrices being concatenated are not consistent.

horzcatMATLAB

Here is the code:
clear all;
a = 1;
b = 2;
alpha = 2;
format longG;
[w,t] = RungeKutta(a,b,0.25,alpha);
combinedArray = [(0:4)' t' w'];
T3 = array2table(combinedArray);
T3.Properties.VariableNames = {'i','t_i','w_i'};
filename1 = 'Table1.csv';
writetable(T3,filename1);
figure('DefaultAxesFontSize',16);
plot(t,w,'LineWidth',2);
xlabel('t');
ylabel('y');
NArray = zeros(1,5);
hArray = zeros(1,5);
errorArray = zeros(1,5);
hFourthArray = zeros(1,5);
for k = 1:5
h = 1/(2^k);
N = (b-a)/h;
[w,t] = RungeKutta(a,b,h,alpha);
error = abs(w(N+1) - TrueSolution(t(N+1)));
NArray(k) = N;
hArray(k) = h;
errorArray(k) = error;
hFourthArray(k) = h^4;
end
combinedArray2 = [hArray' errorArray'];
T4 = array2table(combinedArray2);
T4.Properties.VariableNames = {'h','Error'};
filename2 = 'Table2.csv';
writetable(T4,filename2);
figure('DefaultAxesFontSize',16);
loglog(NArray,errorArray,NArray,hFourthArray,'LineWidth',2);
xlabel('n');
legend('Error','10h^4');

Best Answer

(0:4).' is a 5 x 1 vector. Your t is a 1 x 5 vector, so t' is 5 x 1. So far so good, [(0:4).' t'] is valid giving 5 x 2.
But your w value is a scalar, 1 x 1. w' is a scalar, 1 x 1. You are trying to take the 5 x 2 created so far and add another column to it that is only a single value rather than something with 5 rows.
If you want to copy the scalar w to all of the rows then
combinedArray = [(0:4)', t', w * ones(5,1)];
Related Question