フィルターのクリア

Problem 6. Select every other element of a vector

17 ビュー (過去 30 日間)
Mayla
Mayla 2023 年 9 月 7 日
編集済み: Harald 2023 年 9 月 8 日
Thats the question:
Write a function which returns every other element of the vector passed in. That is, it returns the all odd-numbered elements, starting with the first.
Examples:
Input x = [1 3 2 4 3 5]
Output y is [1 2 3]
Input x = [5 9 3 2 2 0 -1]
Output y is [5 3 2 -1]
Thats the code I wrote:
function y = everyOther(x)
y=[];
t=0.5*length(x);
for n=1:t
y=[z x((2*n)-1)]
end
What is wrong with it? Can you help me? :)

採用された回答

Harald
Harald 2023 年 9 月 7 日
Hi Mayla,
one issue I see: you are using z without having previously defined it.
A key point in MATLAB: you do not need to write a loop for this. This can be accomplished by one indexing operation:
y = x(1:2:end);
Best wishes,
Harald
  2 件のコメント
Mayla
Mayla 2023 年 9 月 7 日
編集済み: Mayla 2023 年 9 月 7 日
Thanks a lot Harald! Is there any other basic learning course except Onramp I can do afterwards?
Harald
Harald 2023 年 9 月 8 日
編集済み: Harald 2023 年 9 月 8 日
Hi Mayla,
on https://matlabacademy.mathworks.com/, you will find a lot of resources. The Onramps are free for everybody. A lot of universities have an agreement to also make the other offerings available to their students and staff at no extra cost.
The natural next step after MATLAB Onramp will be MATLAB Fundamentals.
If you or other readers prefer to have a live instructor to talk to, there is an instructor-led alternative:
If the answer helped you, please kindly "accept" it.
Thank you and best wishes,
Harald

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by