how to write all the for loop outputs in a single vector

5 views (last 30 days)
Hello,
how can I put all the for loop output in a single vector?
For example, there is a question asks to write a function which returns every other elements of the vector passed in, it returns all the odd-numbered elements starting with the first.
input x = [1 2 3 4 5 6 7 8 9]
output y [1 3 5 7 9]
my code:
function y = everyOther(x)
L = length(x)
for i = 1:2:L
y = x(i)
end
end
the output was 9 which was the last thing that has been executed. So how can I put all the executed values in a single vector.
I know that this problem can be solved in one line
y = x(1:2:end)
but I want to know how to solve it with for loop

Accepted Answer

Bruno Luong
Bruno Luong on 11 Aug 2023
function y = everyOther(x)
L = length(x);
i = 1:2:L;
y = zeros(size(i));
for j = 1:length(i)
y(j) = x(i(j));
end
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!