Sum of rows with whose row numbers are specified by another array

I have an array of the form:
TTX =
20 9 2 7
40 10 10 1
60 2 10 9
0 10 5 10
40 7 9 7
40 1 2 8
0 3 5 8
60 6 10 4
20 10 8 7
0 10 10 2
I want to add the elements of rows 1:3, then add the elements of the rows 4:5, then 6:end.
How can I do that?

2 Comments

@Saeid: you just editted your question, removed the original examples, and asked something different from what you originally asked. This discourages people from helping you.
I already answered your original question, but now my answer makes no sense because you removed all of the relevant information.
In future please use comments for adding new information.

Sign in to comment.

 Accepted Answer

From R2015b you can use splitapply:
>> TTX = [...
20 9 2 7
40 10 10 1
60 2 10 9
0 10 5 10
40 7 9 7
40 1 2 8
0 3 5 8
60 6 10 4
20 10 8 7
0 10 10 2];
>> [U,~,X] = unique(TTX(:,1));
>> Y = splitapply(@(x)sum(x,1),TTX(:,2:4),X);
>> M = [U,Y]
M =
0 23 20 20
20 19 10 14
40 18 21 16
60 8 20 13
EDIT: this matches the original question's output explanation and example.

7 Comments

Thanks Stephen, this is exatly what I want, but I tried it now with another array and received an error message. The only difference here is that the new array has 14 rows instead of 10. Here the code:
xx=ceil((rand(14,3))*10)
TT=[20 40 60 0 40 40 0 60 20 0 10 40 40 0]'
ttx=[TT xx]
[U,~,X] = unique(ttx(:,1))
ttx(:,2:4)
Y = splitapply(@sum,ttx(:,2:4),X)
M = [U,Y]
What am I doing wrong?
Guess I found the answer myself: the splitapply line should be changed to:
Y = splitapply(@(x) sum(x,1),ttx(:,2:4),X)
But thanks anyway, your response was what I wnated.
Saeid
"the splitapply line should be changed to:"
You are quite right: if any group has only one line then that error will be thrown (because sum then sums along that row, and not down the columns).
I updated my answer to use this more robust function.
Then please remember to accept my answer!
By all means, you are always a great help!
BTW, Stephen, is it possible to apply splitapply to repmat, so that I could repeat different columns for different numbers of times? E.g., repeat column 1 for 3 times, then repeat column 2 for 5 times, column 3 for 2 times and so on, and the number of repeats given in an array like: [3 5 2 ...]?
@Saeid: read about repelem, use it to generate an index vector. Apply that indexing vector to the column indices of your array:
>> R = [3,5,2];
>> X = repelem(1:numel(R),R);
>> M = randi(9,5,3)
M =
2 6 7
4 1 7
9 8 4
8 9 6
9 7 2
>> M(:,X)
ans =
2 2 2 6 6 6 6 6 7 7
4 4 4 1 1 1 1 1 7 7
9 9 9 8 8 8 8 8 4 4
8 8 8 9 9 9 9 9 6 6
9 9 9 7 7 7 7 7 2 2

Sign in to comment.

More Answers (0)

Categories

Asked:

on 31 May 2019

Commented:

on 10 Jun 2019

Community Treasure Hunt

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

Start Hunting!