필터 지우기
필터 지우기

How to: sum up elements of a row vector into bins of a matrix

조회 수: 7 (최근 30일)
Tero
Tero 2021년 1월 15일
댓글: Cris LaPierre 2021년 1월 18일
Hello,
so I've got a matrix and bin index vectors from histcounts2; I've binned some data over a sphere.
[N,~,~,bx,by]=histcounts2(dataX, dataY, (0:5:180)', (0:5:355)' );
I have another row vector, power, that is equal in length with dataX, dataY, so the bx and by can be used to collect data from this power vector.
Question is, how do I use the bx and by, to generate a matrix out of the power vector, which equals N in size and in terms of the number of elements within bins, but the bin value should be the sum of the elements dedicated for this bin and collected from the power vector?
No loops please.
Thanks,
Tero

채택된 답변

Cris LaPierre
Cris LaPierre 2021년 1월 15일
편집: Cris LaPierre 2021년 1월 15일
With a little creativity, you can use groupsummary. Since you haven't shared enough of your code to use that for an example, here's one modified from an example on the histcount2 documentation page.
% Set up the data
x = randn(100,1);
y = randn(100,1);
[N,~,~,bx,by] = histcounts2(x,y);
% create a 3rd vector, pwr
pwr = randn(100,1);
% Sum the data by grouping pwr by bin numbers by and bx.
% Sum data in the same group.
% Include data for all possible bins
[P,G,C] = groupsummary(pwr,[by,bx],'sum',"IncludeEmptyGroups",true,"IncludeMissingGroups",true);
% Reshape the data to be the same size an N
p = reshape(P,size(N))
p = 5×6
0 1.9431 -0.8699 0.8640 -1.8837 0.0999 0 -1.1247 2.2520 2.9794 2.7351 0 0.1459 -3.4099 2.6683 -1.2993 1.0805 0.9534 2.2462 0.1371 5.2773 0.1546 0 0 0 0 0.1829 2.2118 0 0
N % compare to verify that when N==0, P==0.
N = 5×6
0 2 4 6 4 1 0 7 6 12 6 0 1 6 7 12 6 1 1 2 10 4 0 0 0 0 1 1 0 0
  댓글 수: 2
Tero
Tero 2021년 1월 18일
Perfect! Works like a charm, thank you.
However, I'm facing an annoying dilemma. My script uses CUDA interface to compute some stuff in the GPU. Because my hardware is a few years ols, it forces me to use Matlab 2017b in order to use the hardware. It seems groupsummary was introdued in 2018a. I tried copying the code from current release, but it failed to run in 2017b.
Any solution, or another way of making the grouping? And no, I'm not updating the hardware at this time :)
Tero
Cris LaPierre
Cris LaPierre 2021년 1월 18일
You may be able to achieve something similar using grpstats. You could also try findgroups and splitapply.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by