Filter löschen
Filter löschen

Summing specific values in arrays

2 Ansichten (letzte 30 Tage)
Max
Max am 9 Okt. 2015
Kommentiert: Stephen23 am 10 Okt. 2015
If i have something for example say
2,3
4,5
2,5
1,5
2,1
1,1
how would i sum up all the values on the second column for values of the first column. For example for all the numbers in the first column that have a value 2, I want to some up all the values the second column corresponding to 2. i.e
2,3
2,5
2,1
would be the only things considered and the answer would be (3+5+1) which is 9. These are all the values to the right of 2. I hope this makes sense, and any help would be appreciated.

Akzeptierte Antwort

Thorsten
Thorsten am 9 Okt. 2015
Bearbeitet: Thorsten am 9 Okt. 2015
If you don't need all values you can use the one-liner
s = sum(X(X(:,1)==2, 2));
X(:,1)==2 results in a logical array that has 1's at all the rows that are equal to 2, else zero. If you use this as an index to X(.,2), the values in the 2nd column are selected for those rows in column 1 that equal 2. These values are summed, and you got your desired result.

Weitere Antworten (2)

Stalin Samuel
Stalin Samuel am 9 Okt. 2015
a = [2,3;4,5;2,5;1,5;2,1;1,1]
prompt = 'Enter any no fom first column ';
x = input(prompt)
r = find(a(1:end,1)==x)
rslt = sum(a(r,2))
  1 Kommentar
Max
Max am 9 Okt. 2015
Sorry I'm quite new to matlab I dont really understand the answer.

Melden Sie sich an, um zu kommentieren.


Stephen23
Stephen23 am 9 Okt. 2015
Bearbeitet: Stephen23 am 9 Okt. 2015
This is exactly what accumarray is for:
>> X = [2,3;4,5;2,5;1,5;2,1;1,1]
X =
2 3
4 5
2 5
1 5
2 1
1 1
>> accumarray(X(:,1),X(:,2))
ans =
6
9
0
5
where the first row corresponds to the 1's, the second row the 2's, etc. So it performs all of the sums at once, without any extra code at all! And lets compare to your example, the 2's = 3+5+1 = 9, so it gives the result that you looking for.
Note that the first input to accumarray must be integer indices, so if these are negative or floating point values then you can use unique's third output to generate a vector of integer indices to use for this input.
  2 Kommentare
Max
Max am 9 Okt. 2015
How would I display the answer as just 9 and not in column form :/?
Stephen23
Stephen23 am 10 Okt. 2015
>> Y = accumarray(X(:,1),X(:,2));
>> Y(2)
ans = 9

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by