Sum odd numbers in a matrix

Hello I'm a beginner and just going through some practice problems and I'm on one where I need to sum all the odd values in a matrix. Here's what I have so far.
It passes the first two of three tests, the first where x=[1], the second where x=[2 3 5 7 1 4], but failed when x=[2 3 5 7 1 4;9 1 5 8 3 2]. It failed test 2 when, on line 3, instead of putting length(x) I put x(end), and I'm not really sure why. Any help would be appreciated.
function y = oddsum(x)
v=[];
for i=1:length(x)
g=x(i)
if mod(g,2)==1
v(i)=x(i);
end
end
y = sum(v)
end

回答 (1 件)

madhan ravi
madhan ravi 2020 年 6 月 10 日
編集済み: madhan ravi 2020 年 6 月 10 日

0 投票

v = zeros(size(x)); % good habit is to preallocate
change length to numel that’s why people recommend to use numel() took a while to debug
Whole code can be written as
Wanted = sum(x(mod(x,2) == 1), 'all') % for versions < 2018b sum(sum(...))

カテゴリ

ヘルプ センター および File ExchangeGet Started with MATLAB についてさらに検索

質問済み:

2020 年 6 月 10 日

編集済み:

2020 年 6 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by