Effacer les filtres
Effacer les filtres

Problem 6. Select every other element of a vector

2 vues (au cours des 30 derniers jours)
军 川
军 川 le 27 Avr 2022
Commenté : Matt J le 27 Avr 2022
function x = everyOther(x)
n=length(x)
if mod(x,2)==1
i=1:2:n
expected=[x(i)]
else
i=1:2:n-1
expected=[x(i)]
end
end
This is the code I wrote
Why is this a mistake

Réponses (1)

Matt J
Matt J le 27 Avr 2022
Modifié(e) : Matt J le 27 Avr 2022
It's wrong because you have assumed that IF statements on a vector distribute in some way across the elements of the vector. They don't. The implementation can be done in one line,
function x = everyOther(x)
x=x(1:2:end);
end
  3 commentaires
Matt J
Matt J le 27 Avr 2022
军 川 's reply relocated here:
thank you.it's nice
Matt J
Matt J le 27 Avr 2022
You are quite welcome, but please Accept-click the answer to indicate that it was what you needed.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical 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!

Translated by