MATLAB: The following error occurred converting from double to function_handle: Too many output arguments.

heatequationvector matrix

function heatEquation1D
clf;
clc;
m = 2^8-1; %number of interior spacial gridpoints
T = 5; %final time
%source function
fh=@(x,t)(-24.*x.^2+24.*x+2).*exp(-t).*cos(5.*x)-...
-20.*exp(-t).*sin(5.*x).*(x-0.5);
%fh=@(x,t)25.*pi^2.*cos(5.*x.*pi)+exp(-0.2*t)*4500.*sin(5.*x.*pi).*(...
%exp(5*(t-2))./(exp(5*(t-2))+1)+exp(5*(t-4))./(exp(5*(t-4))+1)+...
%t +exp(5*(t-6))./(exp(5*(t-6))+1)+exp(5*(t-8))./(exp(5*(t-8))+1));
%SSS=@(x)cos(5.*x.*pi)+2.*x-1; %steady-state solution
SSS=@(x,t) x.*(1-x).*cos(5.*x).*exp(-t);
%UFE = cos(rand(m,1)); %initial condition for Forward Euler
UFE = @(x) x.*(1-x).*cos(5.*x);
UBE = UFE; %initial condition for Backward Euler
UTM = UFE; %initial condition for Trap. Method
h = 1/(m+1); %spatial mesh parameter
k = h; %temperal parameter
N = round(T/k); %number of time steps
x = linspace(0,1,m+2); %grid/mesh
M = round(0.005/k); %parameter used for plotting
sI = speye(m);
e = ones(m,1);
A = spdiags([-e 2*e -e],-1:1,m,m)/h^2;
kA = k*A;
subplot(3,1,1)
plot(x,[0;UFE;0]);
title('Forward Euler');
subplot(3,1,2);
plot(x,[0;UBE;0]);
title('Backward Euler');
subplot(3,1,3);
plot(x,[0;UTM;0]);
title('Trap. Method');
pause;
t = 0;
count = 1;
for j=1:N
t = t+k;
F = fh(x(2:(m+1)),t)';
kF = k*F;
UFE = UFE+(-kA*UFE+kF); %FE
UBE = (sI+kA)\(UBE+kF); %BE
UTM = (sI+0.5*kA)\((sI-0.5*kA)*UTM+kF); %TM
if (count>=M) %plot solution
fprintf('t=%3.2e\n', t);
subplot(3,1,1)
plot(x,[0;UFE;0]);
% axis([0 1 -5 7]);
title('Forward Euler');
subplot(3,1,2);
plot(x,[0;UBE;0]);
title('Backward Euler');
axis([0 1 -15 15]);
subplot(3,1,3);
plot(x,[0;UTM;0]);
axis([0 1 -15 15]);
title('Trap. Method');
pause(0.01);
count = 1;
else
count = count+1;
end
end
fprintf('Max Difference compared to steady state solution\n');
fprintf('Forward Euler: %5.4e\n', max(abs(UFE'-SSS(x(2:(m+1))))));
fprintf('Backward Euler: %5.4e\n', max(abs(UBE'-SSS(x(2:(m+1))))));
fprintf('Trap. Method: %5.4e\n', max(abs(UTM'-SSS(x(2:(m+1))))));

Best Answer

plot(x,[0;UFE;0]);
UFE is a function handle. You cannot [] together a numeric value and a function handle.
It is tempting to adjust to
plot(x,[0;UFE(x);0]);
However, UFE(x) is a 1 x 257 vector and you cannot vertcat() a scalar 0 and a 1 x 257 vector.
So from there it is empty to
plot(x,[0, UFE(x), 0]);
and then the [] part will succeed. But then you have the problem that the x is 1 x 257 and the [0,UFE(x),0] would be 1 x 259 because you put the two extra values on it.
It is not clear why you are putting the zeros there.