clear all
clc
clear all
% y' = -3y %
% Exact solution: y = 2*exp(-3x)
% Matlab solution: Follow slope over small x interval (dx) for
% range of x. Small dx should approach exact solution.
dx = 1; % Step size of x
x = 0:dx:10; % Range of x
slope = -3; % Slope of formula, f(y)
y = zeros(size(x)); %Create blank array of y coordinates
y(1) = 2; %y-value at x=0, first (1) value in array
for i = numel(y)
y(i) = y(i-1) + dx*h*y(i-1);
end
disp('y =')
disp (y)
Hello. I just started using matlab (or any other coding program) as a student. Now I ran into a problem:
For a first ode, I have to calculate a function's slope (ax) at a certain y-coordinate and use that slope to mimic the exact solution and plot both to compare.
Starting at y=2, I follow the slope for 1 dx. Slope = -3 y since dy/dx = -3y. Then I get y = 2 - 6 = -4. Then in this point I again calculate the next y-value with the slope in y=-4 and so on. But with my code matlab doesn't do what I want it to do, I've tried many other types of codes but I give up now. :(
What am I doing wrong?
Greetings,
Martijn Jacques

 채택된 답변

the cyclist
the cyclist 2021년 2월 6일

0 개 추천

I didn't look to see if this is the only problem with your code, but a problem is that your for loop has only one iteration. For the above code, it is equivalent to
for i = 11
...
end
I expect you want to do something like
for i = 2:numel(y)
end

댓글 수: 1

Wow that did it for me!
Thank you very much, sometimes it is the simple/smart things I look over.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Functions에 대해 자세히 알아보기

제품

릴리스

R2020a

질문:

2021년 2월 6일

댓글:

2021년 2월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by