MATLAB: Matrix dimensions must agree error

differential equationsgraphmatrix array

I keep getting a 'Matrix demensions must agree error' but I don't know why
h = 0.01;
start = 0;
stop = 7;
x = start:h:stop;
w = zeros(size(x));
M = eye(numel(x)-2) .* cos(x);
K = eye(numel(x)-2) .* -2;
v = ones(1, numel(x)-3);
K1 = diag(v, -1);
K2 = diag(v, 1);
K = K + K1 + K2;
K = K .* (1./(h.*h));
A = K + M;
f = ones(1, numel(x));
f = f .* sin(x);
w = A \ f;
plot(x, w);
grid on;

Best Answer

The eye matrices are (699x699) because of the subtraction by 2 from the size argument. So the vectors all need to be shortened as well, and in the ‘w’ calculation, the ‘f’ vector needs to be truncated by 2 and transposed to a column vector in order for the mldivide operator to work.
Try this:
h = 0.01;
start = 0;
stop = 7;
x = start:h:stop;
w = zeros(size(x));
M = eye(numel(x)-2) .* cos(x(1:end-2));
K = eye(numel(x)-2) .* -2;
v = ones(1, numel(x)-3);
K1 = diag(v, -1);
K2 = diag(v, 1);
K = K + K1 + K2;
K = K .* (1./(h.*h));
A = K + M;
f = ones(1, numel(x));
f = f .* sin(x);
w = A \ f(1:end-2).';
figure
plot(x(1:end-2), w);
grid
.