Find min and max value of vector without using built-in function

6 vues (au cours des 30 derniers jours)
Dan Kristen
Dan Kristen le 19 Sep 2022
Commenté : Dan Kristen le 19 Sep 2022
Hello, I know that this question has been already asked many times, however, I kind of struggle to execute it. Max shows correct result, but the not the minimum value. What could be the solution?
A = [9 6 8 3 6 8 2 1 3 9 1 0 2]
maxval = A(1);
minval = 1;
for i = 1:length(A)
if A(i) > maxval
maxval = A(i);
else A(i) < minval
minval = A(i)
end
end

Réponse acceptée

dpb
dpb le 19 Sep 2022
Modifié(e) : dpb le 19 Sep 2022
...
minval=maxval;
...
if ...
...
elseif A(i) < minval %%% HERE'S YOUR PROBLEM...SEE IT???
...
You missed the "if" part on the "else" clause -- so every thing that wasn't greater than went there and the {A(i) < minval) clause did nothing except display the result of the test to the command line; had no bearing on the logic.
  4 commentaires
Voss
Voss le 19 Sep 2022
The if/elseif should really be two independent ifs if initializing with Infs:
A = 1:10; % strictly increasing -> elseif condition never checked
maxval = -Inf;
minval = Inf;
for i = 1:length(A)
if A(i) > maxval
maxval = A(i);
elseif A(i) < minval
minval = A(i);
end
end
minval,maxval % minval remains Inf
minval = Inf
maxval = 10
A = 1:10;
maxval = -Inf;
minval = Inf;
for i = 1:length(A)
if A(i) > maxval
maxval = A(i);
end
if A(i) < minval
minval = A(i);
end
end
minval,maxval
minval = 1
maxval = 10
Dan Kristen
Dan Kristen le 19 Sep 2022
Thank you so much!

Connectez-vous pour commenter.

Plus de réponses (1)

Matt J
Matt J le 19 Sep 2022
%maxval = A(1);
%minval = 1;
maxval = -inf;
minval = +inf;

Catégories

En savoir plus sur Performance and Memory dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by