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
James Tursa 2015 年 9 月 16 日

0 投票

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
Connor Pomeroy 2015 年 9 月 16 日
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 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.
Matt J
Matt J 2015 年 9 月 16 日
編集済み: Matt J 2015 年 9 月 16 日
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 ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2015 年 9 月 16 日

編集済み:

2015 年 9 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by