Problem 6. Select every other element of a vector
Write a function which returns every other element of the vector passed in. That is, it returns the all odd-numbered elements, starting with the first.
Examples:
Input x = [1 3 2 4 3 5]
Output y is [1 2 3]
Input x = [5 9 3 2 2 0 -1]
Output y is [5 3 2 -1]
Solution Stats
Problem Comments
-
41 Comments
Show
38 older comments
Muhammad
on 26 Aug 2024
Below is my code but it is failing the test 6 and 7. I tried inputting x=randi(100,10,1) and x=primes(20) in the scratchpad and the code works fine, outputing the right answer. There seems to be a problem with the evaluation of the answers.
function y = everyOther(x)
y = [];
for i = 1:2:length(x);
y(end+1) = x(i);
end
Dyuman Joshi
on 29 Aug 2024
@Muhammad, take a deeper look at what the test cases are testing for.
Ivo
on 27 Mar 2025
y = x(1:2:end);
does the trick. :)
Solution Comments
Show commentsProblem Recent Solvers34601
Suggested Problems
-
Sum all integers from 1 to 2^n
16423 Solvers
-
9871 Solvers
-
Flip the vector from right to left
9881 Solvers
-
742 Solvers
-
Converts numbers into characters
1570 Solvers
More from this Author96
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!