Make a vector out of all even/odd numbers from 1 to 100 using for and if
38 次查看(过去 30 天)
显示 更早的评论
Hello, I'm to make two vectors: one consisting of all even numbers between 1 and 100 and one of all the odd numbers. I have to use only simple for and if cycles.
My attempt:
j=1;
k=1;
for i=1:100
if mod(i,2)==0 && i~=1
even(j)=i;
j=j+1;
else
odd(k)=i;
k=k+1;
end
end
even
odd
Now the odd part works well but the even part doesn't. This is what it prints out:
Columns 1 through 22
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44
Columns 23 through 44
46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88
Columns 45 through 66
90 92 94 96 98 100 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
Columns 67 through 88
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
Columns 89 through 100
89 90 91 92 93 94 95 96 97 98 99 100
So it prints all even numbers, which is great, but then it prints every number from 51 to 100. Why? When I type in mod(51,2) it says 1 so the condition doesn't apply.
(Posted on here a couple of minutes ago, hope that's allowed)
0 个评论
回答(5 个)
James Tursa
2018-3-15
编辑:James Tursa
2018-3-15
You probably have left-over variables from a previous run that you are writing into. Clear them out first. E.g., put this at the top of your code:
clear even odd
3 个评论
James Tursa
2018-3-15
Scripts run in your current workspace and leave all resulting variables in your workspace. Sometimes this is what you want, but often it is not. I very seldom use scripts ... almost everything I write is a function, even if it takes no inputs. That way I know I am starting with a fresh workspace for the new code and that I am not corrupting my current workspace. E.g., if your code had been in a file called even_odd.m like this:
function even_odd
% your code
end
you would not have encountered the error that you did. Then if you wanted it to operate on an arbitrary n value and return a result, it is easy to modify. E.g.,
function [even,odd] = even_odd(n)
:
for i=1:n
:
end
Etc.
K. KARTHIK KUMAR
2019-12-16
- Create a vector of all the odd positive integers smaller than 100 in increasing order and save it into variable odds.
- Create a vector of all the even positive integers smaller than or equal to 100 in decreasing order and save it into variable evens.
2 个评论
Lenny C
2020-1-27
For doing the even part initialize the value of k=50 and change for statement to for i=100:-1:1 and change the value of k from k+1 to k-1(this prints even number in reverse order .
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!