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!