Calculate summation using loop?

조회 수: 3 (최근 30일)
Eugene
Eugene 2014년 10월 4일
편집: Eugene 2014년 10월 5일
I'm having trouble trying to put this summation: top of ∑ is N bottom of ∑ is j=1 side of ∑ is j^p For p=1,2,3 and N=6 how do i solve this using matlab? Could i have p=1,2,3 all under one script?
clc
j=1;
p=1;
sum=0;
disp('j p j^p')
disp('-----------------')
while (j<=6)
square=j.^p;
sum=sum+square;
fprintf('%d %d %d\n', j,p,square);
j=j+1;
  댓글 수: 1
per isakson
per isakson 2014년 10월 4일
Why not use a for-loop?

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2014년 10월 4일
편집: Guillaume 2014년 10월 4일
To make it easier for yourself, the first thing you should do is create a function for the summation. It takes two variables (N and p) and returns the result of the summation, like so:
function s = powersum(N, p)
sum = 0;
for j = 1:N
%I'll leave you to fill this in, you've already done that in your script
end
end
You can then use that function in your script for whichever value of N and p you wish:
N = 6;
for p = 1:3
s = powersum(N, p);
%do whatever you want with the result
end
Note that powersum can be implemented more efficiently without a loop but as it looks like you are a beginner in matlab, I'll leave it at that.
  댓글 수: 3
Guillaume
Guillaume 2014년 10월 4일
The whole idea of a function is to make code easier to understand, but you can always replace a function call by the content of the function itself. In your case, just replace the
s = powersum(N, p);
in the for p=... loop with the content of the function, that is:
sum = 0;
for j = 1:N
...
end
Eugene
Eugene 2014년 10월 4일
Yes Guillaume. I understand. Thanks for your help!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by