필터 지우기
필터 지우기

How do you write a finction for TwoSums

조회 수: 4 (최근 30일)
John locke
John locke 2014년 3월 4일
댓글: Jos (10584) 2014년 3월 4일
It should take in an array of numbers and return the sum of odd numbers and the sum of even numbers. For example: [s1 s2] = TwoSums ([3 2 4 7 8]) %should return 10 and 14 [s1 s2] = TwoSums ([-1 -2 9 6 5 8]) %should return 13 and 12

채택된 답변

Chandrasekhar
Chandrasekhar 2014년 3월 4일
편집: Chandrasekhar 2014년 3월 4일
arr = input('enter an array of numbers: ')
[s1 s2] = TwoSums(arr)
Function:
function [sum1,sum2] = TwoSums(arr)
sum1 = 0;
sum2 = 0;
for i = 1:length(arr)
if(rem(arr(i),2)==1)
sum1 = sum1+arr(i);
else
sum2= sum2+arr(i);
end
end
Please Accept the answer
  댓글 수: 1
Jos (10584)
Jos (10584) 2014년 3월 4일
REM is vectorized!
isodd = rem(A,2)==1 % true for odd values in A
s1 = sum(A(isodd)) % sum of odd values
s2 = sum(A(~isodd)) % sum of even values

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by