Make specific array from another array elements
조회 수: 6 (최근 30일)
이전 댓글 표시
The problem:
''Write a m.file which is asking to enter array X (integer numbers),which will make a new array Y .Elements of the array Y are sum from even digits of elements array X. If some element of array X is not inteneger,make a comment about error.
For example X = [81, 19, 102, 22, 12, 21] Y = [8, 0, 2, 4, 2, 2]
From my knowlege i would do it smh like this.
x=input('input array X');
y=[]
s=0
for i=1:length(x)
while k<0
k=(i)
d=rem(k,10)
if rem(d,2)==0
s=s+d
k=fix(k,10)
y=[k]
I know its not working,but logic of my solution is.
We took first element of the array x.
There is a k that will have same value.There is a d which will be our detector of the digit ,if that number can be divide with 2 ,it means that its even,so s(sum) will be s+that number.After that we need to take a look over next digit of the first element.We are doing that by shorting fix/floor function,,and doing it until the we get to the zero.
When we got the zero,we are moving to next element.
But i would be super grateful if someone can solve this for me ,because i just need to see the logic how it works
댓글 수: 0
답변 (1개)
Walter Roberson
2022년 9월 19일
while k<0
You did not initialize k.
You are testing that k is less than 0. But the next statement, k=(i) changes k to something that is going to be positive. Unless you change it to be something negative inside your if, the while loop will exit the next time through because whatever k you are left with will not be < 0
You are intended to be working with the elements of x, but you never index x
k=fix(k,10)
fix() does not accept a second argument.
You need to have code to move on to the next digit. And that code needs to happen even if the mod() test failed.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!