If-condition: if number is +-5% of another

9 次查看(过去 30 天)
I'm trying to set an if-condition like that:
for x = 1:1:size(t{n})
if t{n}.sh(x) = +-0.05 t{n}.DiffMileagekm(x) %here is where I am trying to get the condition
somecalculation
end
end
E.g. sh(1) = 50 and DiffMileagekm(1) = 49, sh is in the range of +-5% of Diffmileagekm and therefor the calculation will be performed.
Is there a way to do that?
  1 个评论
Lukas Netzer
Lukas Netzer 2021-5-16
I now set the if-condition like that:
if (t{n}.sh(x) >= 0.95 * t{n}.DiffMileagekm(x)) && (t{n}.sh(x) <= 1.05 * t{n}.DiffMileagekm(x))
Is there a better way to do that - or is it just fine like that?

请先登录,再进行评论。

采纳的回答

Jan
Jan 2021-5-16
编辑:Jan 2021-5-16
Are you sure, that this is correct:
for x = 1:1:size(t{n})
if t{n}.sh(x) = ...
Does t{n}.sh have as many elements as the size of t{n} is?
Note: 1:size(X) might not do, what you expect. size(X) replies a vector. 1:[a,b] replies 1:a and ignores b. This is at least confusing. Prefer numel(X) or specify the dimension with size(X, 1).
If you code is really correct, this would do what you are asking for:
sh = t{n}.sh; % Easier to read and faster
DiffM = t{n}.DiffMileagekm;
for x = 1:size(t{n}, 1)
if abs((sh(x) - DiffM(x))) < 0.05 * DiffM(x) % [EDITED]
...
end
end

更多回答(1 个)

Image Analyst
Image Analyst 2021-5-16
Your if statement is not proper. For one thing you don't have a * in front of the t. Secondly you're using = instead of ==. Third, +- doesn't mean plus or minus -- it means minus (if it even works). Fixed code:
for x = 1:1:size(t{n})
difference = abs(t{n}.sh(x) - t{n}.DiffMileagekm(x)); % abs() takes care of plus or minus (above or below)
if difference < (0.05 * t{n}.DiffMileagekm(x))
% Difference is less than your threshold so do something.
somecalculation
end
end
You might also look at the ismembertol() function.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by