Euler Method for vector function
3 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!