sum of array by specific index value

조회 수: 26(최근 30일)
Khairul Nur
Khairul Nur 2021년 5월 29일
편집: KALYAN ACHARJYA 2021년 5월 29일
hi, i have two array. First array containing index and second array (hasil_tambah_array) containing the value to be sum-up as below:
index =
4
2
4
hasil_tambah_array =
3.6881
0.8506
0.0132
0.8506
10.5147
12.5147
14.5074
21.8003
11.2145
18.5074
I try to sum the second array as per index such as 3.6881,0.8506,0.0132 and 0.8506 (since the 1st index is 4) will be sum together . Then 10.5147 and 12.5147 (since the 2nd index is 2) will be sum up and respectively (next will be the rest since the index is 4).
Appreciate ur time to solve this. TQIA.

채택된 답변

DGM
DGM 2021년 5월 29일
편집: DGM 2021년 5월 29일
This is one way. It's probably not the most efficient way, but it does the job.
idx = [4 2 4];
H = [3.6881 0.8506 0.0132 0.8506 10.5147 12.5147 14.5074 21.8003 11.2145 18.5074].';
S = cellfun(@sum,mat2cell(H,idx,1))
S = 3×1
5.4025 23.0294 66.0296
Bear in mind that using mat2cell() to subdivide the main vector requires that sum(idx) = numel(H), so watch out for that.
  댓글 수: 1
Khairul Nur
Khairul Nur 2021년 5월 29일
mat2cell working great! TQ!

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

추가 답변(1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 5월 29일
편집: KALYAN ACHARJYA 2021년 5월 29일
result=sum(second_arary(first_array))
More
result=sum(hasil_tambah_array(index))
  댓글 수: 2
KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 5월 29일
index =[4
2
4];
hasil_tambah_array =[3.6881
0.8506
0.0132
0.8506
10.5147
12.5147
14.5074
21.8003
11.2145
18.5074];
result=sum(hasil_tambah_array(index))
Output:
result =
2.5518
More: Same as
>> 0.8506+0.8506+0.8506
ans =
2.5518

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

Community Treasure Hunt

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

Start Hunting!

Translated by