Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

Summing array entries 1

Status
Not open for further replies.

JohnKGH

Civil/Environmental
Jul 26, 2005
12
Hey guys,

This is the opposite of my last question. How do you find sums of consecutive array entries? I need them to be displayed however and therefore cannot use the sume function. By this I mean [4 5 6 7] = [9 11 13]
Ultimately I want to use diff(x).*(sums of y).
 
Replies continue below

Recommended for you

Code:
A = [4 5 6 7];
answer = A(1:end-1) + A(2:end);
M

--
Dr Michael F Platten
 
It looks to me like you are doing numerical integration. If this is the case, take a look at Matlab's existng trapz() function.
 
I don't think so. trapz returns a single value and cumtrapz would not give the required answer.

M

--
Dr Michael F Platten
 
Let's wait and see. If the next question is: "Is there a way to sum all the elements of a vector and divide by two?" then I win!
 
Guys I tried
for i = 1:1:length(array)-1
answer = x(i)+x(i+1)
end

Would this be a correct approach?
 
No. For 2 reasons.

1) "answer" is being overwritten each time you go through the loop

2) You are using an unnecessary "for" loop

This is pretty basic stuff. I realise you are new to Matlab, but have you tried reading any books on the subject?

M

--
Dr Michael F Platten
 
Yea Mike, im reading a MATLAB intro book for engineers. Unfortunately Im just beginning to program this week. BTW, your way definitely worked. So what you are saying is a for loop only gives one answer after many repetitions of mathematical calculation? Thanks
 
No, he's saying YOUR loop produces that result.

TTFN



 
JohnKGH,

Take a look at the sum() function. It looks purpose-built for your problem.
 
replace
answer = x(i)+x(i+1)

with
answer(i) = x(i)+x(i+1)

OR

answer = x(1:end-1)+ x(2:end)

which is the vector based approach as given by Mickey P
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor