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!
回答(1 个)
James Tursa
2015-9-16
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 个评论
Connor Pomeroy
2015-9-16
James Tursa
2015-9-16
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;
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!