Percentage difference in matlab
169 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (1)
Nicolas B.
am 23 Okt. 2019
Bearbeitet: Nicolas B.
am 23 Okt. 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!