How do I refer to only the odd-numbered elements in any given vector?

129 ビュー (過去 30 日間)
Emily Hornbuckle
Emily Hornbuckle 2015 年 2 月 3 日
回答済み: MD ZIHADUL ISLAM TUSAR 2022 年 10 月 3 日
Given a vector I want to write a function that only refers to the odd-numbered elements in that given vector. How would I do this?
  1 件のコメント
Stephen23
Stephen23 2015 年 2 月 3 日
What is an "odd-numbered" element? An element for which the index is odd (keep in mind that MATLAB uses one-based indexing!), or where the element value itself is odd?

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

回答 (2 件)

Star Strider
Star Strider 2015 年 2 月 3 日
I’m not certain what you mean by ‘odd-numbered elements’, so here are two possibilities:
v = [10:20];
oddidx = @(v) v(1:2:end); % Addressing Odd-Indexed Elements
oddval = @(v) v(rem(v,2) == 1); % Addressing Odd-Valued Elements
y1 = oddidx(v)
y2 = oddval(v)
produces:
y1 =
10 12 14 16 18 20
y2 =
11 13 15 17 19

MD ZIHADUL ISLAM TUSAR
MD ZIHADUL ISLAM TUSAR 2022 年 10 月 3 日
function y = everyOther(x)
n=length(x);
y=x(1:2:n);
end

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by