Counting every other number in a list

10 ビュー (過去 30 日間)
Nathaniel Wolff
Nathaniel Wolff 2020 年 9 月 12 日
コメント済み: the cyclist 2020 年 9 月 12 日
Howdy.
I have a matrix
mylist = [1:10]
I need to count every other number in this matrix
I can't use the odd or even distinguishing tests such as...
for i = 1:length(mylist)
if rem(mylist(i),2) ~= 0;
eo_total = eo_total + 1
end
end
Because this only counts the odd numbers in my for loop. So if I had a matrix
mylist(2) = [ 2 4 6 8 10]
eo_total = 0 instead of 2
any ideas?

採用された回答

the cyclist
the cyclist 2020 年 9 月 12 日
I'm not sure what you mean by "count" them, but the following vector will store every other element from mylist, starting with the first one:
out = mylist(1:2:end)
  2 件のコメント
Nathaniel Wolff
Nathaniel Wolff 2020 年 9 月 12 日
by count I mean that litterally. I want to count every other other digit in my matrix.
for instance
[1 2 3 4 5]
Ideally i would have a function that would output 2. Becuause if I start at 1, not counting itself, the next other number would be 3 then the last is 5. But I can't have it be odd or even because this list might be something disproportionalty even or odd.
thank you for the code, I can just use a length(out) to count the number of digits in this new matrix.
that's actually much simpler then what I was trying to do with for loops
the cyclist
the cyclist 2020 年 9 月 12 日
Oh. Then it's probably more efficient to do
ceil(numel(mylist)/2)
Then you don't need to create a second vector.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by