Sum odd numbers in a matrix

10 views (last 30 days)
Joshua Saenz
Joshua Saenz on 10 Jun 2020
Edited: madhan ravi on 10 Jun 2020
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

Answers (1)

madhan ravi
madhan ravi on 10 Jun 2020
Edited: madhan ravi on 10 Jun 2020
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(...))

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!