Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
How to sum variable number of elements in vector

Subject: How to sum variable number of elements in vector

From: Donald

Date: 14 Apr, 2011 19:48:07

Message: 1 of 3

Suppose I have a vector x = rand(1,n) and I have a matrix Y = size(m,2) and I want to create sums according to the rows of the matrix Y, where the number of elements in each row is variable. Is there an efficient way to compute this?

Example, x = [1:10]; y = [1 2; 3 5; 6:10];
I want z(1) = sum(x(1:2));
          z(2) = sum(x(3:5));
          z(3) = sum(x(6:10));

Subject: How to sum variable number of elements in vector

From: Matt J

Date: 14 Apr, 2011 20:18:05

Message: 2 of 3

"Donald " <gt4715b@yahoo.com> wrote in message <io7j1n$q1v$1@fred.mathworks.com>...
>
> Example, x = [1:10]; y = [1 2; 3 5; 6:10];
> I want z(1) = sum(x(1:2));
> z(2) = sum(x(3:5));
> z(3) = sum(x(6:10));

The following can be efficient, assuming that in realistic examples, y does repeated table-lookup of all the elements of x,


 csums=[0,cumsum(x)];
 
 upper=y(:,2)+1;
 lower=y(:,1);
 
 z=csums(upper)-csums(lower),

Subject: How to sum variable number of elements in vector

From: Donald

Date: 15 Apr, 2011 18:15:22

Message: 3 of 3

"Matt J" wrote in message <io7kpt$ktc$1@fred.mathworks.com>...
> "Donald " <gt4715b@yahoo.com> wrote in message <io7j1n$q1v$1@fred.mathworks.com>...
> >
> > Example, x = [1:10]; y = [1 2; 3 5; 6:10];
> > I want z(1) = sum(x(1:2));
> > z(2) = sum(x(3:5));
> > z(3) = sum(x(6:10));
>
> The following can be efficient, assuming that in realistic examples, y does repeated table-lookup of all the elements of x,
>
>
> csums=[0,cumsum(x)];
>
> upper=y(:,2)+1;
> lower=y(:,1);
>
> z=csums(upper)-csums(lower),

Thanks. This is exactly what I was looking for.

Tags for this Thread

No tags are associated with this thread.

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.

Contact us