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
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!