Percentage difference in matlab

202 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by