loop iteration in matlab

5 views (last 30 days)
Zeynep Toprak
Zeynep Toprak on 20 Nov 2020
Commented: Rik on 20 Nov 2020
I have the following polynomial
F(x) = 1^5 + (1^5 + 2^5)+ (1^5 + 2^5 + 3^5) + ... + (1^5 + 2^5 + 3^5 + 4^5 + ... + x^5)
How can I write a loop iteration for this polynomials?
  1 Comment
Stephen23
Stephen23 on 20 Nov 2020
Why do you need a loop?
1^5 + (1^5 + 2^5) + (1^5 + 2^5 + 3^5) + (1^5 + 2^5 + 3^5 + 4^5)
ans = 1610
sum(cumsum((1:4).^5))
ans = 1610

Sign in to comment.

Accepted Answer

KSSV
KSSV on 20 Nov 2020
Edited: KSSV on 20 Nov 2020
x = 10 ;
thesum = 0 ;
for i = 1:x
thesum = thesum+sum((1:i).^5) ;
end
  5 Comments
Zeynep Toprak
Zeynep Toprak on 20 Nov 2020
btw, your code gives wrong result:(
KSSV
KSSV on 20 Nov 2020
Hey..yes there is a typo error in the code. I have edited it now.

Sign in to comment.

More Answers (1)

Rik
Rik on 20 Nov 2020
I would suggest not using a loop:
F=@(x) sum( ( (1:x).^5 ).*(x:-1:1) );
  2 Comments
Zeynep Toprak
Zeynep Toprak on 20 Nov 2020
this is with vectorization method?
Rik
Rik on 20 Nov 2020
Yes, and the code posted by Stephen in a comment is also vectorized.
There are probably some exceptions I'm not thinking of, but if you don't see a loop (or cellfun/arrayfun) the code is vectorized.

Sign in to comment.

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!