Sum elements over indices in cell array

조회 수: 5 (최근 30일)
Lennart Sinjorgo
Lennart Sinjorgo 2022년 6월 10일
댓글: Matt J 2022년 6월 11일
I have a cell array, in which each cell is a vector of integer numbers. These numbers are certain indices of another vector, say A. For each cell, I want to compute the sum of the elements in A, which are being indexed by my cell. For example, I can easily do this with a for loop (see code below). However, I was wondering if it is possible to vectorize this piece of code.
What I have done now, is artificially edit the cells so that they have the same length, by adding a dummy index. This dummy index then refers to a value 0 in vector A, so that I can easily sum over them by indexing A with the matrix induced by the cell array. However, this takes up a lot of memory.
Any ideas?
A = 1:15;
% some vector containging the values I need
myCell = {[1 3 4], [2 5 8 12]};
% the cell array generally contains arrays of different lengths
sumValues = zeros(1,2);
% I want to fill the array SumValues efficiently
for j = 1:2
sumValues(j) = sum(A(myCell{j}));
end
  댓글 수: 2
Rik
Rik 2022년 6월 10일
Loops can be surprisingly fast if there isn't a straightforward way to vectorize your code. Did you run any profiling to see if this is actually the bottleneck in your process?
Lennart Sinjorgo
Lennart Sinjorgo 2022년 6월 11일
Yes, its rather time consuming, although definitely not the bottleneck. That doesn't mean I shouldn't look for ways to speed it up though.

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

채택된 답변

Matt J
Matt J 2022년 6월 10일
편집: Matt J 2022년 6월 10일
Once you've split things into cells, there is nothing faster than a loop. The better data organization would be to use group labels instead:
A = 1:15;
I = [1 3 4, 2 5 8 12]; %The indices as a vector
G= [1 1 1, 2 2 2 2]; %Group labels
sumValues=accumarray(G(:),A(I(:)))
sumValues = 2×1
8 27
  댓글 수: 2
Lennart Sinjorgo
Lennart Sinjorgo 2022년 6월 11일
Thank you! I did not know of this function! I'll have a look and see if it's faster than what I'm doing right now.
Matt J
Matt J 2022년 6월 11일
You're welcome, but if you conclude that it works well for you, please Accept-click the answer.

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by