Error using plot Vectors must be the same length.
1 view (last 30 days)
Show older comments
Huda Alzaki
on 12 Oct 2019
Answered: Fabio Freschi
on 12 Oct 2019
I got an error when attempting to plot errors E1 and E2. I used hold on command but still I got the same error
function RungeKuttaMethod
%example of Runge-Kutta method of order 4.
%y' = y - t^2 + 1.
a = 0; %time interval we are solving over
b = 2;
N = 4; %number of steps
t = zeros(1, N); %preallocate memory for these variables - this is preferred but is not required to work%
w = zeros(1, N);
w(1) = 0.5; %initial value of w.
h = (b - a)/N; %step size
t(1) = a; %initial vlaue for time.
syms Q
F = @(t, y) y - t^2 + 1; %thing we are solving.
clc
fprintf ('x(n) \t \t \t y \t \t \t \t y(n) \t \t \t E1(n) \n') % data table header
for i = 1:N
K1 = h*(F(t(i), w(i))); %this is the RungKutta Method.
K2 = h*(F(t(i) + 0.5*h, w(i) + 0.5*K1));
K3 = h*(F(t(i) + 0.5*h, w(i) + 0.5*K2));
K4 = h*(F(t(i) + h, w(i) + K3));
w(i+1) = w(i) + (K1 + 2*K2 + 2*K3 + K4)/6;
t(i+1) = a + i*h;
Q(i+1) = t(i+1)^2 + 2*t(i+1) +1 -(0.5)*exp(t(i+1)); %actualy solution we ca use to compare between both methods%
E1(i+1)= abs(w(i+1) - Q(i+1));
fprintf('%f \t \t %f \t \t %f \t \t%f \t \t \n',t(i+1),Q(i+1),w(i+1), E1 (i+1))
end
% plot(t, E1)
N = 40;
t = zeros(1, N); %preallocate memory for these variables - this is preferred but is not required to work%
w = zeros(1, N);
w(1) = 0.5; %initial value of w.
h = (b - a)/N; %step size
t(1) = a; %initial vlaue for time.
syms Q
F = @(t, y) y - t^2 + 1;
fprintf ('x(n) \t \t \t y \t \t \t \t y(n) \t \t \t E2(n) \n') % data table header
for i = 1:N
K1 = h*(F(t(i), w(i))); %this is the RungKutta Method.
K2 = h*(F(t(i) + 0.5*h, w(i) + 0.5*K1));
K3 = h*(F(t(i) + 0.5*h, w(i) + 0.5*K2));
K4 = h*(F(t(i) + h, w(i) + K3));
w(i+1) = w(i) + (K1 + 2*K2 + 2*K3 + K4)/6;
t(i+1) = a + i*h;
Q(i+1) = t(i+1)^2 + 2*t(i+1) +1 -(0.5)*exp(t(i+1)); %actualy solution we ca use to compare between both methods%
E2(i+1)= abs(w(i+1) - Q(i+1));
fprintf('%f \t \t %f \t \t %f \t \t%f \t \t \n',t(i+1),Q(i+1),w(i+1), E2 (i+1))
end
hold on
plot(t, E1, t, E2)
0 Comments
Accepted Answer
Fabio Freschi
on 12 Oct 2019
Some comments
1) Q is defined twice as symbolic variable, but it is actually an array
2) in the first loop N = 4, so length(t) = 4 and length(E1) = 4; [btw: the real length is 5 because i = 1 is not addressed: your index is always i+1]. In the second loop N = 40, so length(t) = 40 and length(E2) = 40. In the end you use the same t for plottin either E1 and E2.
My suggestion is to use different vectors for the first and second loop, maybe t1 and t2. Then preallocate always your vectors. Finally in the loop, address Q(i) and E1(i) (and E2) instead of Q(i+1) and E1(i+1)
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!