Euler Method for vector function

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

Steven Lord
Steven Lord 2023년 1월 26일
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
Askic V 2023년 1월 26일
From the code it can be seen that at least one end is missing, i.e. the for loop is not ended.
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.
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,:));

댓글을 달려면 로그인하십시오.

답변 (1개)

Askic V
Askic V 2023년 1월 26일

0 개 추천

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

카테고리

질문:

Erm
2023년 1월 26일

댓글:

Erm
2023년 1월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by