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

5 次查看(过去 30 天)
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

采纳的回答

Bruno Luong
Bruno Luong 2023-8-11
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by