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

1 visualizzazione (ultimi 30 giorni)
Lukas Netzer
Lukas Netzer il 16 Mag 2021
Modificato: Jan il 16 Mag 2021
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 Commento
Lukas Netzer
Lukas Netzer il 16 Mag 2021
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?

Accedi per commentare.

Risposta accettata

Jan
Jan il 16 Mag 2021
Modificato: Jan il 16 Mag 2021
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

Più risposte (1)

Image Analyst
Image Analyst il 16 Mag 2021
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.

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by