Thread Subject: conditional sum

Subject: conditional sum

From: Johannes Deelstra

Date: 9 Nov, 2009 21:05:22

Message: 1 of 5

Hei

I have a matrix dd(5559 x 2). dd(1:365,1) = 1993, dd(366:730,1)=1994, etc.
dd(1:31,2) =1:31, dd(32:59,2)=1:29. I want the cumsum of dd(:,2) under the condition that dd(:,1)== 1993, dd(:,1)=1994, etc. How do I do this?

Johannes

Subject: conditional sum

From: ImageAnalyst

Date: 9 Nov, 2009 21:43:56

Message: 2 of 5

On Nov 9, 4:05 pm, "Johannes Deelstra" <johannes.deels...@bioforsk.no>
wrote:
> Hei
>
> I have a matrix dd(5559 x 2). dd(1:365,1) = 1993, dd(366:730,1)=1994, etc.
> dd(1:31,2) =1:31, dd(32:59,2)=1:29. I want the cumsum of dd(:,2) under the condition that dd(:,1)== 1993, dd(:,1)=1994, etc. How do I do this?
>
> Johannes

--------------------------------------------------
With this tiny amount of data you could write it yourself with a
simple for loop. That could be the most intuitive, straightforward,
understandable, and readable way to do it. Should be lightning fast
for an array as small as this.

Or you can use the find() function to find indexes that you want to
include, and then use logical indexing to extract out just those
elements (or rows) and then pass that into the cumsum() function.

Subject: conditional sum

From: arun

Date: 9 Nov, 2009 23:33:26

Message: 3 of 5

On Nov 9, 10:05 pm, "Johannes Deelstra"
<johannes.deels...@bioforsk.no> wrote:
> Hei
>
> I have a matrix dd(5559 x 2). dd(1:365,1) = 1993, dd(366:730,1)=1994, etc.
> dd(1:31,2) =1:31, dd(32:59,2)=1:29. I want the cumsum of dd(:,2) under the condition that dd(:,1)== 1993, dd(:,1)=1994, etc. How do I do this?
>
> Johannes

idx = find(dd(:,1) == 1993); % gives the indices corresponding to 1993
s = cumsum(dd(idx,2)); % cumulatively sums the values corresponding to
the indices obtained in step 1 for column 2.

best, arun.

Subject: conditional sum

From: Jan Simon

Date: 10 Nov, 2009 09:26:02

Message: 4 of 5

Dear Johannes!

> idx = find(dd(:,1) == 1993);
> s = cumsum(dd(idx,2));

You can even shorten Arun's method:
  s = cumsum(dd(dd(:,1) == 1993, 2));

Jan

Subject: conditional sum

From: Loren Shure

Date: 10 Nov, 2009 13:30:53

Message: 5 of 5

In article <hdbbja$p8b$1@fred.mathworks.com>,
matlab.THIS_YEAR@nMINUSsimon.de says...
> Dear Johannes!
>
> > idx = find(dd(:,1) == 1993);
> > s = cumsum(dd(idx,2));
>
> You can even shorten Arun's method:
> s = cumsum(dd(dd(:,1) == 1993, 2));
>
> Jan
>


You can look for multiple years with ismember instead of find.


--
Loren
http://blogs.mathworks.com/loren

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

Contact us at files@mathworks.com