Hi there,
I have written a mathematical code to calculate the trapezium rule for a set function. For my entire program, I have attempted to make it as 'user-friendly' as possible; whereby all variables are set upon running the code. This way, the script does not need to be editted in any way – see my code if you're confused in any way.
The issue I have is that when I input the actual mathematical 'function' into the program, it keeps being called multiple times, when I only want it to be called once. For example, if the function I needed evaluating was: 2x^2, I would input ' 2*x.^2 ', but would have to do this several times instead of once.
I think that the number of times the program calls upon this input is related to the number of strips to calculate – try this and see if you think I'm right? Therefore, I believe the loop inside the script keeps calling the mathematical 'function' user input continuously – I don't know how to stop this from happening?
I am a beginner to MATLAB and whilst it appears that I'm overcomplicating everything, I'm only trying to make everything as 'user-friendly' as possible…
My script: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
disp('Trapezium Rule Calculator'); disp('Truth and Absolute Values'); disp('-------------------------'); disp(' '); % F. Variables
a = input('Enter the value of the lower bound:'); b = input('Enter the value of the upper bound:'); n = input('Enter the number of strips required:'); disp(' '); h = ((b - a)/ (n)); % Summation of First and Last Tra.
sum = 0.5*( f(a) + f(b) ); % Loop for Middle Tra.s
for i = 1 : n-1; sum = sum + f(a+i*h); end % Truth - Integral Calculation
g = @f; truth = integral(g,a,b); disp(' '); disp('Actual Value of Integral:'); disp(truth); % Final Value of Tra.
Answer = h*sum; ModAnswer = abs(Answer); disp('Value of Trapezium Area Calculated:'); disp(ModAnswer); % Difference (Accuracy)
ModTruth = abs(truth); diff = abs( ModTruth - ModAnswer); disp('Difference in Calculation:'); disp(diff); % Percentage Accuracy
format short PInaccuracy = ( (diff) / (ModTruth) )*100; PA = 100 - PInaccuracy; disp('Percentage Accuracy (%):'); disp(PA); % Functions Formulae
function y = f(x) y = input('Enter function for processing:'); end
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Please help me on how to solve this issue please?
Thank you!
Best Answer