Matrix Dimension doesn't agree: Please kindly help to review this code it keep saying matrix dimension must agree. Thanks.

% User Specified Information
% Number of Fourier Modes
N = 16 ;
% Temporal Domain and Stepsize
t0 = 0; tend = 10; dt = .01;
t = (t0:dt:tend);
% Spatial grid (used in evaluation of exact solution)
x = (0:.01:1)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create Initial Fourier Coefficients - u(x,0) in fourier basis
n = (1:N)';
a(:,1)= -12*(-1).^n./(pi^3*n.^3);
[t, a] = ode45(@getRHS, t, a); a = a';
% Use numerical fourier coefficients to create numerical solution and
% create exact solution
u = zeros(numel(x),numel(t)); u0 = x-(x.^3); uexact(:,1) = u0;
for(i=1:numel(t))
for(n=1:N)
% Exact Solution
uexact(:,i+1) = uexact(:,i)+1 + (-12*(-1).^n)/(pi^3 * n.^3)*sin(n*pi*x)*exp(1-(n*pi)^2*t(i));
% Numerical Solution
u(:,i) = u(:,i) + a(n,i)*sin(n*pi*x);
end
if(t(i) == 1)
fprintf('u(.5,1) = %f. \n', u( (numel(x)-1)/2+1, i))
end
uexact(:,i) = uexact(:,i) + a(n,i)*sin(n*pi*x)*exp(1-(n*pi)^2*t(i));
end
size(u)
size(uexact)
size(x)
size(t)
% Visualization Requirement
figure(1), clf
mesh(t,x,abs(u-uexact))
xlabel('t')
ylabel('x')
zlabel('|u - uexact|')
title('Absolute Error in Spectral Projection Method')
end
function da = getRHS(t,a)
N = size(a);
for(n=1:N)
da(n,1) = -(n*pi)^2*a(n) + 1/pi*(1-(-1)^n)/n;
end
end

2 Comments

N = size(a);
is a a row or a column? because size with one input and one output always returns a vector and you are using that vector as a bound in for. You might know how it works today but by next week you will have forgotten. use numel instead of size

Sign in to comment.

 Accepted Answer

Change the call to mesh() like this
mesh(t,x,abs(u-uexact(:,1:end-1)))

2 Comments

Can you please "Accept this answer" to give Ameer credit (reputation points) and thanks for helping you? Thanks in advance.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!