calculating percentage change function

19 views (last 30 days)
Sarah K
Sarah K on 22 Oct 2019
Commented: dpb on 22 Oct 2019
Hi,
I am high school china. want to build a function for two input variables (two judges scores) and calculate the percentage difference between them.
function [outcome] = judges_scores(input1, input2)
pct_difference = 100*(input1-input2)./input2);
if (pc_difference = 0)
disp('pass');
else (pc_difference < 0) && (pc_difference > 0)
disp('fail');
end
I would like some assistance, especially how to calculate percentage difference for two inputs in a function. Thank you.
  1 Comment
dpb
dpb on 22 Oct 2019
Your function calculates the percentage difference between the two judges' scores presuming the second is the reference. What you'll get as a numeric value will depend on which is the reference...if the reference is higher than the other, you'll get a value <0 of somewhat smaller absolute magnitude than vice versa:
>> J1=95;J2=92;
>> (J1/J2-1)*100
ans =
3.2609
>> (J2/J1-1)*100
ans =
-3.1579
>>
How to treat this is up to your problem definition which isn't given so we can't answer that part.
NOTA BENE:
You defined the percent difference as pct_difference, however you missed the t on pct in the |if...else...end clause so it's undefined.
You also called your function return value outcome but it is never defined in the function so don't have any return value.

Sign in to comment.

Answers (1)

Rik
Rik on 22 Oct 2019
You should use = for an assignment and == for a comparison. Another point is that you don't need a conditional for an else, only for an elseif.
Note that a comparison with 0 might lead to unexpected results in edge cases. Comparing the abs to eps should be more reliable (and would provide an easy way to modify your tolerance.

Community Treasure Hunt

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

Start Hunting!