How to create a function using matlab code?

1 view (last 30 days)
beth
beth on 20 Apr 2014
Answered: Walter Roberson on 20 Apr 2014
Hellooooo, for a project at university I have to be able to let the user type in a function for a variable x. However I'm not sure how to do this and after reading up on it, it has confused me as you do with us blondes. I was wondering if anyone would be able to write some of the code so i could see where i was going wrong. This is my code underneath for numerical integration and help would be so so appreciated. Thank you!!! :)
% Implentation of Rectangle, Trapezium and Simpson's Rule
% a: lower bound, b: upper bound, N: number of strips
clear,
fprintf(' \n Numerical Integration');
fprintf(' \n Input values for integral boundaries a and b with a<b')
fprintf(' \n a = '); a= input('');
fprintf(' \n b = '); b= input('');
if a > b;
fprintf(' \n a has to be less than the value of b')
fprintf(' \n Input new values for a and b')
fprintf(' \n a = '); a= input('');
fprintf(' \n b = '); b= input('');
end
fprintf(' \n Input the number of strips')
fprintf(' \n N = '); N= input('');
R(1)=a;R(2)=b;
x = linspace(R(1), R(2),N);
fx = input('type in f(x)=');
h = (b-a)/N;
mpr = 0;
tr = 0;
for i = 1:(N-1);
mpr = mpr+fx(floor(i))*h; %midpoint rule
tr = tr+(fx(i)+fx(i+1))/2*h; %trapazoidal rule
end

Answers (2)

Star Strider
Star Strider on 20 Apr 2014
This should get you started:
abtest = 1;
k1 = 0;
while (abtest == 1) & (k1 <= 10)
a = input('Type a value for limit ‘a’: ');
b = input('Type a value for limit ‘b’: ');
abtest = a > b;
if abtest == 1
fprintf('\n\tThe limit ‘a’ must be less than ‘b’\n\n')
end
k1 = k1 + 1;
end
k1 = 0;
Ntest = 0;
while (Ntest == 0) & (k1 <= 10)
N = input('Type a value for the number of strips (must be greater than zero: ')
Ntest = gt(N, 0)
k1 = k1 +1;
end
fprintf(1,'\n\n\tIntegrating...\n\n')
Its logic is straightforward. I added a counter, limits, and logical checks to be sure your integration routine received the correct information.

Walter Roberson
Walter Roberson on 20 Apr 2014
You have not repaired the code according to the problem I described earlier, http://www.mathworks.co.uk/matlabcentral/answers/126162#answer_133703

Categories

Find more on Chemistry in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!