From: Johannes Deelstra on
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
From: ImageAnalyst on
On Nov 9, 4:05 pm, "Johannes Deelstra" <johannes.deels...(a)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.
From: arun on
On Nov 9, 10:05 pm, "Johannes Deelstra"
<johannes.deels...(a)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.
From: Jan Simon on
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
From: Loren Shure on
In article <hdbbja$p8b$1(a)fred.mathworks.com>,
matlab.THIS_YEAR(a)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