How do I use a sum function in a for loop?
3 次查看(过去 30 天)
显示 更早的评论
x = [1, 23,43, 72, 87, 56, 98, 33]
Find:
1) Use a for loop to sum the elements in the vector
2) Repeat the previous problem, this time using a while loop
3) Use a for loop to create a vector of the squares of the numbers 1 through 5.
4) Use a while loop to create a vector of the squares of the numbers 1 through 5.
5) Use the primes function to create a list of all the primes below 100. Now use a for loop to multiply adjacent values together.
2 个评论
Geoff Hayes
2015-4-15
Milanna - rather than posting your homework question, why not post what you have tried to solve this problem? See loop control structures for details on how to construct for and while loops.
回答(1 个)
Saurabh
2023-5-29
1.
total = 0; % Initialize the accumulator variable
for i = 1:length(x)
total = total + x(i);
end
2.
total = 0;
i = 1;
while i <= length(x)
total = total + x(i);
i = i + 1;
end
3.
squares = zeros(1, 5);
for i = 1:5
squares(i) = i^2;
end
4.
i = 1;
square = zeros(1, 5);
while i <= 5
squares(i) = i^2;
i = i + 1;
end
5.
primes_list = primes(100)
for i = 1:length(x) - 1
prime_list(i) = prime_list(i) * prime_list(i + 1);
end
%actually fifth question is not very clear, what the output structure, can
%you provide a little more detail about this.
0 个评论
另请参阅
类别
在 Help Center 和 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!