basic knowledge question for loops

write a for loop that fills in this vector (all zeros, length 5) with the squares of the integers from 1 to 5. This for loop should iterate over 1 to 5, square each one, and add it to the vector.
How would I go about doing this? I have
a= zeros(1,5)
b= [1 2 3 4 5]
for i= 1:5
y= b.^ i
a= sum(y
end
but im confused on how to add each component to itself as it is going through the loop. If you could explain your code, that would be appreciated!

Answers (1)

You made a decent start so I will help. Your code paired up with the instructions:
a= zeros(1,5)
b= [1 2 3 4 5]
for i= 1:5 % iterate over 1 to 5
y= b.^ i % square each one
a= sum(y % add it to the vector
end
The "iterate over 1 to 5" looks good.
The "square each one" I think means square each index. So instead of b.^i you would have i^2.
The "add it to the vector" I think means add it to the corresponding spot in a. So a(i) = a(i) + y.

3 Comments

how can a(i) be on both sides of the equation? That doesn't make sense. So, b(i)= a(i) +y?
a(i) being on both sides of the equation makes perfect sense. It does exactly what the instructions say: "add it to the vector". "it" in this case is y. The "vector" in this case is a. The spot in question is the i'th spot. So the expression "a(i) + y" adds y to the i'th spot of a, and then stores the result right back into the i'th spot of a.
how can a(i) be on both sides of the equation? That doesn't make sense.
It is not an equation (this is code), it's an assignment operation.
However, I think what is really being asked for is
a(i)=y;

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 16 Sep 2015

Edited:

on 16 Sep 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!