Question: I keep getting the following error code in my MATLAB code, and I can not figure out how to fix it . Below is the

I keep getting the following error code in my MATLAB code, and I can not figure out how to fix it. Below is the error code I keep receiving, followed by my MATLAB code. What do I need to change in my code to correct the problem?
Error using fzero (line 308)
Initial function value must be finite and real.
Error in main (line 18)
z0= fzero(@(z0) shooting_method(x, z0, L, sigma_prime, T_inf, T0, TL), z0_guess);
MATLAB CODE:
function main()
L =10; % Length of the rod (m)
N =100; % Number of spatial grid points
% Constants
sigma_prime =2.7e-9; % K^-3 m^-2
T_inf =298; % K
% Boundary conditions
T0=400; % K at x=0
TL =600; % K at x=L
% Spatial grid
x = linspace(0, L, N+2); % Including boundary points
% Shooting Method
z0_guess =0.01; % Initial guess for z(0)
z0= fzero(@(z0) shooting_method(x, z0, L, sigma_prime, T_inf, T0, TL), z0_guess);
[~, T_shooting]= shooting_method(x, z0, L, sigma_prime, T_inf, T0, TL);
% Finite Difference Method
T_fd = finite_difference_method(L, N, sigma_prime, T_inf, T0, TL);
% Plotting
figure;
plot(x, T_shooting, 'b-', 'LineWidth', 2);
hold on;
plot(x, T_fd,'r--', 'LineWidth', 2);
hold off;
xlabel('x (m)');
ylabel('Temperature (K)');
title('Temperature Distribution in a Rod');
legend('Shooting Method', 'Finite Difference Method');
grid on;
end
function [residual, T]= shooting_method(x, z0, L, sigma_prime, T_inf, T0, TL)
% Shooting Method Solver
% Number of spatial grid points
N = length(x)-2;
% Spatial step size
dx = L /(N +1);
% Initialize y and z vectors
y = zeros(N+2,1);
z = zeros(N+2,1);
% Set initial conditions
y(1)= T0;
z(1)= z0;
% Numerical integration using Euler's method
for i =1:N+1
z(i+1)= z(i)+ dx *(-sigma_prime *(T_inf - y(i)^4));
y(i+1)= y(i)+ dx * z(i+1);
end
% Calculate the residual at the right boundary (x=L)
residual = y(end)- TL;
T = y;
end
function T = finite_difference_method(L, N, sigma_prime, T_inf, T0, TL)
% Finite Difference Method Solver
% Spatial grid
x = linspace(0, L, N+2); % Including boundary points
% Spatial step size
dx = L /(N +1);
% Coefficient matrix for finite difference equation
A = diag(-2*ones(N,1))+ diag(ones(N-1,1),1)+ diag(ones(N-1,1),-1);
A = A / dx^2;
% Right-hand side vector
b = sigma_prime *(T_inf - T0^4)* ones(N,1);
b(1)= b(1)- T0/dx^2;
b(end)= b(end)- TL/dx^2;
% Solve the system of equations
T_interior = A\b;
% Concatenate the boundary conditions to get the final temperature profile
T =[T0; T_interior; TL];
end

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!