필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Saeid
Saeid 2019년 5월 31일
댓글: Saeid 2019년 6월 10일
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
Stephen23
Stephen23 2019년 5월 31일
@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.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2019년 5월 31일
편집: Stephen23 2019년 5월 31일
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
Stephen23
Stephen23 2019년 5월 31일
편집: Stephen23 2019년 5월 31일
@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
Saeid
Saeid 2019년 6월 10일
Thanks again, Stephen!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by