using bayes design the function function tn= true_negative(sens, spec, prior) that calculates the probability of a negative test to be correct using bayes rule in matlab

main.m
function tn = true_negative(sens, spec, prior)
% Calculates the probability of a negative test to be correct using Bayes Rule
% sens - sensitivity of the test
% spec - specificity of the test
% prior - prior probability of the event
% tn - probability of a true negative test

% probability of a positive test result given that the event occurred: 
% p(pos|E) = sens
% probability of a negative test result given that the event did not occur: 
% p(neg|¬E) = spec
% prior probability of the event: 
% p(E) = prior
% prior probability of not event: 
% p(¬E) = 1 - prior

% applying Bayes Rule, the probability of the event given a positive test result is:
% p(E|pos) = p(pos|E) * p(E) / p(pos)
% p(pos) = p(pos|E) * p(E) + p(pos|¬E) * p(¬E)
% p(pos|¬E) = 1 - spec

% probability of a negative test result given that the event did not occur: 
% p(neg|¬E) = spec
% probability of a negative test result given that the event occurred: 
% p(neg|E) = 1 - sens

% applying Bayes Rule, the probability of the event given a negative test result is:
% p(¬E|neg) = p(neg|¬E) * p(¬E) / p(neg)
% p(neg) = p(neg|E) * p(E) + p(neg|¬E) * p(¬E)
% p(neg|E) = 1 - sens

pos = sens * prior + (1 - spec) * (1 - prior); % probability of a positive test result
neg = (1 - sens) * prior + spec * (1 - prior); % probability of a negative test result

tn = neg / (neg + pos); % probability of a true negative test
end
1391 chars
37 lines

To use this function, call it with the desired values of sensitivity, specificity, and prior probability. For example:

main.m
tn = true_negative(0.9, 0.8, 0.1);
35 chars
2 lines

This will return the probability of a negative test to be correct given a sensitivity of 0.9, specificity of 0.8, and prior probability of 0.1.

gistlibby LogSnag