x=-4:0.01:4
t= [0.2 0.4 0.6 0.8 1.0];
figure(1)
hold on
for i= 1:5
u(i,:)= exp (x/2)*(1+(t*(-256+240-108+27)/128)+(t.^2*(168-24+27)/128)+((t.^3/3)*((-16+9)/64))+((t.^4/4)*(1/128)))
plot(x,u(i,:))
end
grid on
xlabel(‘x’)
ylabel(‘t’)
legend(‘t=0.1’,’t=5’,’t=100’, ‘Location’, ‘best’)
tittle(‘Absolute Error of u(x,t) at 0<t<1)

Answers (2)

Image Analyst
Image Analyst on 15 Dec 2017
Edited: Image Analyst on 15 Dec 2017
So many problems.
  1. x and t aren't the same length.
  2. Using * and / instead of .* and ./
  3. Not preallocating the size of u in advance so it knows how many columns there are.
  4. using some kind of funky symbol for the single quote.
  5. no such function as tittle(). Use title() instead.
And read this so you know how to format your code so we can read it: http://www.mathworks.com/matlabcentral/answers/13205#answer_18099
Guillaume
Guillaume on 15 Dec 2017
Edited: Guillaume on 15 Dec 2017
As it is, your i loop is pointless as the only thing that depends on i is the row of u where you put the result. So, even if there was no error, you'd end up with five identical rows in u, since you're calculated five times the exact same thing.
I strongly suspect that you meant to have each row of u to correspond to the respective t value, in which case
  • you shouldn't hardcode the end bound of the loop, but instead make it depend on the size of t
  • you need to index t in the loop
As Image Analyst also said, preallocated u would be better, so:
u = zeros(numel(t), numel(x)); %preallocation
for i = 1:numel(t) %don't hardcode end bounds, make is equal to the size of t
%note I haven't check that the following is correctly written, I've just copy/pasted your
%original equation and added the (i) indexing
u(i, :) = exp(x/2)*(1+(t(i)*(-256+240-108+27)/128)+(t(i)^2*(168-24+27)/128)+((t(i)^3/3)*((-16+9)/64))+((t(i)^4/4)*(1/128)));
plot(x, u(i, :));
end
But note that the loop is altogether not necessary, you could calculate the whole u in one go, which as a result doesn't have to be preallocated.
%in R2016b or later:
t = t'; %transpose so that it is a column vector
u = exp(x/2) .* (1+(t*(-256+240-108+27)/128)+(t.^2*(168-24+27)/128)+((t.^3/3)*((-16+9)/64))+((t.^4/4)*(1/128)))
plot(x, u);
%in earlier version without implicit expansion:
t = t'; %transpose so that it is a column vector
u = bsxfun(@times, exp(x/2), 1+(t*(-256+240-108+27)/128)+(t.^2*(168-24+27)/128)+((t.^3/3)*((-16+9)/64))+((t.^4/4)*(1/128)));
plot(x, u);

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!