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

5 ビュー (過去 30 日間)
Nourhan
Nourhan 2023 年 8 月 11 日
コメント済み: Nourhan 2023 年 8 月 11 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by