If-condition: if number is +-5% of another
1 次查看(过去 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?
采纳的回答
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
0 个评论
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!