Percentage difference in matlab

조회 수: 171 (최근 30일)
Sarah K
Sarah K 2019년 10월 23일
편집: Nicolas B. 2019년 10월 23일
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.

답변 (1개)

Nicolas B.
Nicolas B. 2019년 10월 23일
편집: Nicolas B. 2019년 10월 23일
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by