Why does following code don't give any output?

 Akzeptierte Antwort

Rik
Rik am 13 Apr. 2022
Because the number 3 doesn't exist in your array:
data=0.1:0.1:12;
[~,ind]=min(abs(data-3));
data(ind)
ans = 3.0000
Now, that looks like 3, but let's investigate if it is exactly 3:
data(ind)-3
ans = 4.4409e-16
Close, but not exact. Since you used ==, Matlab will only give you the fprintf if the match is exact.
The solution is to use a tolerance.
for i =0.1:0.1:12
if abs(i-3)<(10*eps)
fprintf('Hello\n')
end
end
Hello

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2021a

Gefragt:

am 13 Apr. 2022

Beantwortet:

Rik
am 13 Apr. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by