# Add Cells/Matrices Row by Row

2 views (last 30 days)

Show older comments

### Answers (1)

dpb
on 13 Aug 2021

"matrix of about 600,000 rows and 14 columns. This data is a 6000 different bins with 100 columns each. So what I am trying to do is add (Row1 + Row101+ Row201....+..), (Row2 + Row 102+ Row 202 + ....) and get a final matrix of 100x14. "

Using your smaller example, but same logic works, the "dead ahead" solution is

>> x=rand(12,2) % some sample data

x =

0.8147 0.9572

0.9058 0.4854

0.1270 0.8003

0.9134 0.1419

0.6324 0.4218

0.0975 0.9157

0.2785 0.7922

0.5469 0.9595

0.9575 0.6557

0.9649 0.0357

0.1576 0.8491

0.9706 0.9340

>>

% the engine

N=4; % number of elements in group

M=size(x,1)/N; % number of bins -- must be evenly divisible

S=zeros(M,size(x,2); % preallocate

for i=1:M

S(i,:)=sum(x(i:N:end,:));

end

Show what we got...

>> S

S =

2.4046 2.0347

1.9682 1.4368

0.5631 2.4416

>>

>> x(1,1)+x(5,1)+x(9,1) % illustrate first term gets right answer...

ans =

2.4046

>>

##### 2 Comments

dpb
on 13 Aug 2021

Edited: dpb
on 13 Aug 2021

So, switch N from 4 to 3 -- but that's not what your example asked...

"Now what I wanted to do is to bin 4 rows together. So we have 3 bins like below, "

The logic is generic regardless of the size as long as size(data,1)/N is integer.

>> N=3; % changed mind, groups of 3, not four

>> M=size(x,1)/N; % compute # bins given N

>> S=zeros(M,2); % preallocate again

>> for i=1:M,S(i,:)=sum(x(i:N:end,:));end % and compute

>> S % what we get

S =

2.9715 1.9270

2.2426 2.7158

2.1526 3.3057

2.1568 0.9698

>> x(1,1)+x(4,1)+x(7,1)+x(10,1) % again, just check got it right...

ans =

2.9715

>>

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!