MATLAB Answers

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

1 view (last 30 days)
Saeid
Saeid on 31 May 2019
Commented: Saeid on 10 Jun 2019
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

Sign in to comment.

Accepted Answer

Stephen
Stephen on 31 May 2019
Edited: Stephen on 31 May 2019
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

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!