Correct indexing in a for loop - my array fills gradually?
Show older comments
I have a sequence from 1 to 100 in increments of 2. I am trying to write a for loop to multiply all even numbers by 3 and square all odd numbers. I have to use a for loop.
So far I have:
a=1:2:100;
e=zeros(1,15);
o=zeros(1,15);
for
i=1:15
if a(rem(a,2)==0);
e(i)=a(i)*3
end
if a(rem(a,2)==1);
o(i)=a(i)^2
end
end
I want to generate the answers for each and store them in the e and o variables.
What am I doing wrong?
2 Comments
Stephen23
on 19 Nov 2018
"I have a sequence from 1 to 100 in increments of 2. I am trying to write a for loop to multiply all even numbers by 3 and square all odd numbers."
Note that all values in that sequence are odd, so all you need is this:
a.^2
Image Analyst
on 19 Nov 2018
Essentially a duplicate of this question: Click Here
I'm guessing it's a class homework.
Answers (1)
"What am I doing wrong?"
You are using a logical array as an if condition... unfortunately this is allowed, but makes no sense for your algorithm. Your indexing returns elements of a in a vector, which you then use as the if condition, but this requires all of the condition elements to be true, in order to execute the code inside the if.
if a(rem(a,2)==0);
^^ ^ Why are you indexing into a? How does this work?
The proper MATLAB solution is just to use logical indexing without a loop, e.g.:
>> b = 1:100;
>> m = mod(b,2);
>> b(m==1) = b(m==1).^2;
>> b(m==0) = b(m==0)*3;
2 Comments
Victoria Moorcroft
on 19 Nov 2018
b = 5:17;
disp(b)
for k = 1:numel(b)
if mod(b(k),2) % note the indexing here!
b(k)=b(k).^2;
else
b(k)=b(k).*3;
end
end
disp(b)
Giving b at the start:
5 6 7 8 9 10 11 12 13 14 15 16 17
and then at the end:
25 18 49 24 81 30 121 36 169 42 225 48 289
I made a few changes to make the code simpler than what you were trying to do, but the most important chagne (regarding your original question) is the indexing used with the if condition.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!