How do I use a sum function in a for loop?
3 views (last 30 days)
Show older comments
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 Comments
Geoff Hayes
on 15 Apr 2015
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.
Answers (1)
Saurabh
on 29 May 2023
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!