This topic has been permanently closed and transferred to MATLAB Answers.

Contests
Follow


JAMEEL

Error at , can not run M = A\b;

JAMEEL on 24 Nov 2023 (Edited on 27 Nov 2023)
Latest activity Reply by Omar on 25 Nov 2023

% Given data
x = [2.0, 3.0, 6.5, 8.0, 12, 15];
f = [14, 20, 17, 16, 23, 125];
% Construct the cubic spline
h = diff(x);
A = zeros(length(x)-2);
for i = 1:length(x)-2
A(i,i) = 2*h(i) + 2*h(i+1);
A(i,i+1) = h(i+1);
A(i+1,i) = h(i);
A(i+1,i+1) = 2*h(i) + h(i+1);
end
b = [6*(f(2)-f(1))/h(1) + 6*(f(3)-f(2))/h(2);
6*(f(4)-f(3))/h(3) + 6*(f(5)-f(4))/h(4)];
M = A\b;
% Evaluate the second derivative at data points
d2f_dx2 = zeros(length(x),1);
for i = 1:length(x)-2
d2f_dx2(i) = M(i);
d2f_dx2(i+1) = M(i) + h(i)*M(i+1);
d2f_dx2(i+2) = M(i) + 2*h(i)*M(i+1) + h(i)*h(i)*M(i+2);
end
% Display second derivatives at data points
disp('Second Derivatives at Data Points:');
disp(d2f_dx2);
Omar
Omar on 25 Nov 2023 (Edited on 27 Nov 2023)
The MATLAB code you provided is intended to construct a cubic spline and calculate the second derivatives at data points. However, there are a few issues in the code which could be causing the error.
1. Matrix A Construction: The loop for constructing matrix `A` is not set up correctly. The current loop may not fill the matrix `A` properly, especially the last row and column.
2. Vector b Construction: The vector `b` is not constructed correctly. The current implementation only considers two values, but it should consider all the interior points.
3. Calculating Second Derivatives: The loop for calculating the second derivatives (`d2f_dx2`) is not correctly set up and might result in an index out-of-bounds error.
Here's the corrected MATLAB code:
% Given data
x = [2.0, 3.0, 6.5, 8.0, 12, 15];
f = [14, 20, 17, 16, 23, 125];
% Construct the cubic spline
h = diff(x);
n = length(x) - 2;
A = zeros(n, n);
b = zeros(n, 1);
% Constructing matrix A
for i = 1:n
if i < n
A(i, i+1) = h(i+1);
A(i+1, i) = h(i+1);
end
A(i, i) = 2 * (h(i) + h(i+1));
end
% Constructing vector b
for i = 1:n
b(i) = 6 * ((f(i+2) - f(i+1)) / h(i+1) - (f(i+1) - f(i)) / h(i));
end
% Solve for M
M = A\b;
% Evaluate the second derivative at data points
d2f_dx2 = zeros(length(x), 1);
d2f_dx2(2:end-1) = M;
% Display second derivatives at data points
disp('Second Derivatives at Data Points:');
disp(d2f_dx2);
**Please accept the answer if you like it and it runs well. It will increase my rank.

See Also