필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
Lukas Netzer
Lukas Netzer 2021년 5월 16일
편집: Jan 2021년 5월 16일
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