XM551
XM551

Reputation: 103

How to add some value in the specific range in a matrix?

How to add the value in specific range in a matrix?

I mean if i have a matrix

Columns 1 through 7

 4     4     4     4     4     4     4
48    48    48    48    48    48    48

Columns 8 through 14

 4     4     4    13    13    13    13
48    48    48    57    57    57    57

Columns 15 through 20

13    13    13    13    13    13
57    57    57    57    57    57

I want to sum all 4 values ,all 13 values,all 48 values,and all 57 values,so the result should be m=[40 130 480 570]

The easiest but stupid method is like this

a=sum(1,(1:10));

b=sum(1,(11:20));

c=sum(2,(1:10));

d=sum(2,(11:20));

m=[a b c d]

If i want to write a code with for-loop or while-loop to show the result i want.how do i write the code?

Or can i use the some method to write a code without loop to show this?

Upvotes: 0

Views: 101

Answers (2)

rinkert
rinkert

Reputation: 6863

Though the solution of @phnx works fine, you can also use the other outputs of the unique function in combination with accumarray as described in the docs:

[C, ~, ic] = unique(a);
a_counts = accumarray(ic,1);
m = C.*a_counts

This will avoid the warning 'hist' is not recommended...

Upvotes: 4

phnx
phnx

Reputation: 459

A simple two-line solution, with A as your original matrix, would be:

[a,b]=hist(A(:),unique(A(:)))
c = a .* b'

with a containing the number of occurances, b the unique elements and c the sums.

Upvotes: 3

Related Questions