Euler Method for vector function
Mostrar comentarios más antiguos
I'm tring to apply Euler method to vector function and I'm facing error in the loop. How it can be fixed?
h=0.1;
n=5;
yexact=@(x) [cos(x); sin(x); - sin(x); cos(x)]; % the exact function
s = size(x);
rows = s(1);
% the loop for solve DE
for j = 1: rows
y = zeros(1 , rows);
Y(1,:) = [1; 0 ; 0 ; 1]; %intial condition
x = linspace(0,0.5,n+1);
for i=1:rows
f = [-sin(i); cos(i); - cos(i); -sin(i)]; % y'= f
y(i+1,: ) = y(i, :) + h * f(x(i),Y(i,:)); % Euler method
end
% apply Euler method to differnt step sizes
hh(j) = h;
h = h/2;
n = (0.5)/h;
4 comentarios
Steven Lord
el 26 de En. de 2023
What is the full and exact text of the warning and/or error messages you receive when you run this code? Please show all the text displayed in orange and/or red in the Command Window as they may be useful in determining what's going on and how to avoid the warning and/or error.
Askic V
el 26 de En. de 2023
From the code it can be seen that at least one end is missing, i.e. the for loop is not ended.
Erm
el 26 de En. de 2023
Erm
el 26 de En. de 2023
Respuestas (1)
It appears to me that you want this:
clear
clc
close all
% step size
h = 0.1;
% final time
Tf = 5;
x = 0:h:Tf;
yexact = {@(x) cos(x); @(x) sin(x);@(x) -sin(x); @(x) cos(x)}; % the exact function
nr_functions = size(yexact,1);
% Solving y' = f(x)
funcs = {@(x) -sin(x); @(x) cos(x);@(x) -cos(x); @(x) -sin(x)};
% Initial conditions
y = zeros(nr_functions, numel(x));
y(:,1) = [1; 0; 0; 1];
for i = 1:nr_functions % loop goes through functions
for j = 1:numel(x)-1 % loop for each particular function
y(i, j+1) = y(i, j) + h * funcs{i}(x(j));
end
end
% Plot results
for i = 1: nr_functions
subplot(nr_functions,1,i);
plot(x, y(i,:));
hold on
plot(x, yexact{i}(x));
legend ('Euler method', 'Exact');
end
Categorías
Más información sobre Numbers and Precision en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
