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!

Respuestas (1)

James Tursa
James Tursa el 16 de Sept. de 2015
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 comentarios

Connor Pomeroy
Connor Pomeroy el 16 de Sept. de 2015
how can a(i) be on both sides of the equation? That doesn't make sense. So, b(i)= a(i) +y?
James Tursa
James Tursa el 16 de Sept. de 2015
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.
Matt J
Matt J el 16 de Sept. de 2015
Editada: Matt J el 16 de Sept. de 2015
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;

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 16 de Sept. de 2015

Editada:

el 16 de Sept. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by