Given a vector containing N integers, write an M-flies to calculate how many elements in this vector are odd and how many are even. example if the given vector is :
2 ビュー (過去 30 日間)
古いコメントを表示
input_v=[27 43 55 95 42 98 31]
%your program should output the following messages:
>>The number of odd elements is 5.
>>The number of even elements is 2.
N=128;% is the length of the vector is assumed to be 128.
input_v =ceil(rand(1,N)*100);
%%%I TRY MANY WAYS BOT IS NOT WORKING!!!!! help please!!!
採用された回答
Stephen23
2017 年 3 月 14 日
>> input_v = [27;43;55;95;42;98;31];
>> fmt = 'The number of %s elements is %d\n';
>> fprintf(fmt,'odd',nnz(mod(input_v,2)==1))
The number of odd elements is 5
>> fprintf(fmt,'even',nnz(mod(input_v,2)==0))
The number of even elements is 2
その他の回答 (1 件)
ES
2017 年 3 月 14 日
disp(['The number of even elements is ', num2str(length(input_v(mod(input_v,2)==0)))]);
disp(['The number of odd elements is ', num2str(length(input_v(mod(input_v,2)~=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!