Euler Method for vector function

조회 수: 3 (최근 30일)
Erm
Erm 2023년 1월 26일
댓글: Erm 2023년 1월 26일
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
Erm
Erm 2023년 1월 26일
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 2023년 1월 26일
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일
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by