Use for loop array value to return into for loop

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

 Accepted Answer

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 Comment

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

Sign in to comment.

More Answers (0)

Categories

Find more on Functions in Help Center and File Exchange

Products

Release

R2020a

Community Treasure Hunt

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

Start Hunting!