If-condition: if number is +-5% of another
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
Réponse acceptée
Jan
le 16 Mai 2021
Modifié(e) : Jan
le 16 Mai 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
0 commentaires
Plus de réponses (1)
Image Analyst
le 16 Mai 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!