How to create two lists one with the even and another with odd numbers on a vector
1 次查看(过去 30 天)
显示 更早的评论
I want to introduce a vector and then get two vector one with the even numbers and another with odd numbers from the vector i introduced.This is the script.
count_odd=0
count_even=0
i=1
for vetor=input('Introduce the vector :')
if rem(vetor,2)~=0
count_odd=count_odd+1
list_odd(i)=vetor(i)
elseif rem(vetor,2)==0
count_even=count_even+1
list_even=count_even+1
end
end
disp(count_odd)
disp(count_even)
0 个评论
采纳的回答
Walter Roberson
2022-11-27
i=1
%...
list_odd(i)=vetor(i)
You never increase i so you are always writing to the same output location. If you did increase i you would run into the problem that at any one time, vetor will be a scalar, unless the user inputs something with more than one row, so vetor(i) would typically fail when i is not 1. If the user does happen to input something with multiple rows, then you would run into the problem that rem(vetor,2)~=0 would be a vector condition and if on a vector condition does not do what you would want it to do.
You also do not initialize list_odd so after everything if no odd values were found, then list_odd would not exist to examine.
list_even=count_even+1
You are overwriting list_even with the scalar value count_even+1 rather than storing values of vetor into it. And same problem with not initializing.
if rem(vetor,2)~=0
elseif rem(vetor,2)==0
When you use if and elseif the implication is that there are some cases in which both branches could fail, that it is possible that neither condition might be true. Under what conditions could rem(vetor,2) not (not equal 0) but rem(vetor,2)==0 also fail ? Answer: it could happen if vetor is a symbolic variable; it can also happen if vetor is non-scalar (because the input vector had more than one row.) If you are certain that you are working with numeric scalars, then you should probably use if/else rather than if/elseif
Hint: you can store into a variable indexed at count_odd
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!