function y = f(x)The file should be saved as f.m. Warning, do not abuse the use of f.m, you can use f1.m, f2.m, f3.m ... for different function.
y = cos(x); % or other function
return
The derivative of the function f'(x) can be defined as
function y = fp(x)The function should be named as fp.m
yp = -sin(x); % or other function
return
The second type is an algorithm file, for example, if we use the forward Euler's formula, we can write
function y = feuler(x,h) % x and h are inputs, y is the outputThe file should be saved as feuler.m.
y = (f(x+h)-f(x))/h; % You need f.m is defined.
return
The third type of files are called script file, say hw1.m whose contents are
h=1; x=pi/4; k=1; while h>1e-17 % A conditional loop [et1,et2,et3] = feuler(x,h); e1(k) = et1; h1(k)=h; % save the data k = k+1; h = h/2; end
e1, % Show the date (error)
loglog(h1,e1); % Plot the error versus
help diffIf it is used, you can use something like my_diff