# Euler function where you can define equation, starting x and y values, number of steps and the step length

6 ビュー (過去 30 日間)
Heine Rugland 2020 年 3 月 26 日
コメント済み: Heine Rugland 2020 年 3 月 26 日
This is what I have thus far
function [xverd, tilnaer] = Euler_met (f,x0,y0,no_steg,lengde)
g = @(x,y) f;
t = x0:0.01:x0+no_steg;
y = zeros(1,length(t));
y(1) = y0;
fprintf('\n x y ')
for s = 1:length(t)-1
fprintf('\n%4.3f %4.3f ',t,y)
y(s+1) = y(s)+lengde*g(t(s),y(s));
end
plot(t,y)
end
But when I try to run it with these values:
Euler_met(8*cos(x+y),0,4,10,0.01)
I get this error:
Undefined operator '*' for input arguments of type 'function_handle'.
y(s+1) = y(s)+lengde*g(t(s),y(s));
I've tried just defining the equation f in line 3 in the code as such:
g = @(x,y) 8*cos(x+y);
And that works perfectly, so why can I replace the equation as seen in the code at the top?

### 採用された回答

Torsten 2020 年 3 月 26 日
Use g = f or g = @(x,y) f(x,y) instead of g = @(x,y) f.

#### 3 件のコメント

Heine Rugland 2020 年 3 月 26 日
for g = @(x,y) f(x,y) I get:
Index in position 1 is invalid. Array indices must be positive integers or logical values.
g = @(x,y) f(x,y);
y(s+1) = y(s)+dt*g(t(s),y(s));
For g = f I get:
Index in position 1 is invalid. Array indices must be positive integers or logical values.
y(s+1) = y(s)+dt*g(t(s),y(s));
Torsten 2020 年 3 月 26 日
Of course, f should already be a function handle
Euler_met(@(x,y)8*cos ...,0,4,10.0.1)
Heine Rugland 2020 年 3 月 26 日
Thank you so much!