Effacer les filtres
Effacer les filtres

Percentage difference in matlab

89 vues (au cours des 30 derniers jours)
Sarah K
Sarah K le 23 Oct 2019
Modifié(e) : Nicolas B. le 23 Oct 2019
Hi,
I have two variables (both scaler input) to use in a formula. How can I calculate the percentage difference between and make a 'if percentage difference is higher than x%, display 'good' etc. Maybe I must use a loop? Thank you.

Réponses (1)

Nicolas B.
Nicolas B. le 23 Oct 2019
Modifié(e) : Nicolas B. le 23 Oct 2019
Hey Sarah,
The following code could help you:
diff = x2 - x1; % x2 and x1 are your input variables. x1 is reference and x2 the value to compare
relDiff = diff / x1;
if abs(relDiff) > tolerance % e.g. 0.01 for 1%
disp('good');
else
disp('bad');
end
This code is based on the assumption that x1 and x2 are scalar. If x2 is not scalar (x1 can be scalar or same size as x2):
relDiff = (x2 - x1) ./ x1; % it is not a matrix division but an element-wise division
[I, J] = find(abs(relDiff) > tolerance); % return all indexes of elements that are out of range
% check if any value is out of range
if ~isempty(I)
% display the list of values out of range
for n = 1:numel(I)
fprintf('Index [%d,%d] is out of tolerance'. I(n), J(n));
end
else
% display good because all values are in the range
disp('good, here have a biscuit :)');
end
Hope it helps
Regards

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by