Euler Method for vector function

3 views (last 30 days)
Erm
Erm on 26 Jan 2023
Commented: Erm on 26 Jan 2023
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 Comments
Erm
Erm on 26 Jan 2023
error in line16 which is corresponging to the loop
>> Euler2
Error: File: Euler2.m Line: 16 Column: 1
At least one END is missing. The statement beginning here does not have a matching end.
Erm
Erm on 26 Jan 2023
I end the loop and I have another error
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in Euler2 (line 23)
y(i+1, : ) = y(i,: ) + h * f(x(i),Y(i,:));

Sign in to comment.

Answers (1)

Askic V
Askic V on 26 Jan 2023
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!