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:
Sum selected elements of a vector

Subject: Sum selected elements of a vector

From: Jeff

Date: 14 Mar, 2013 23:06:06

Message: 1 of 3

Hi guys,

How can I sum the elements (row 1 + row 2 & row 3 + row 4) of a 4 x 1 vector and have a 2 x 1 vector as output?

The 'sum' function does not work as it will sum up all the elements and provide a single value. See example..

Thanks!

Example:

A=[row 1; row 2; row 3; row 4]

I am trying to obtain:

B=[row 1 + row 2; row 3 + row 4];

Subject: Sum selected elements of a vector

From: james bejon

Date: 14 Mar, 2013 23:59:07

Message: 2 of 3

% One way (I'm certain there are betters):
r = rand(4, 6);
x1 = squeeze( sum( reshape(r.', size(r, 2), [], 2), 2 ) ).';

Subject: Sum selected elements of a vector

From: Jos (10584)

Date: 15 Mar, 2013 07:10:05

Message: 3 of 3

"Jeff " <jeffong@rocketmail.com> wrote in message <khtl4u$aff$1@newscl01ah.mathworks.com>...
> Hi guys,
>
> How can I sum the elements (row 1 + row 2 & row 3 + row 4) of a 4 x 1 vector and have a 2 x 1 vector as output?
>
> The 'sum' function does not work as it will sum up all the elements and provide a single value. See example..
>
> Thanks!
>
> Example:
>
> A=[row 1; row 2; row 3; row 4]
>
> I am trying to obtain:
>
> B=[row 1 + row 2; row 3 + row 4];

I would recommend something simple like

A = rand(4,1) ;
B = [sum(A(1:2,:)) ; sum(A(3:4,:))]

~ Jos

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