Add data of a matrix based on an other matrix
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Philipp Wirtz
el 11 de Mayo de 2018
Comentada: Philipp Wirtz
el 11 de Mayo de 2018
I would like to add a certain amount of data points of one matrix in a new matrix, based on a third matrix. It is because I need to add data points from one day (it is not predefined how many datapoints there are going to be) and then go to the next day and do the same. This is the code I tried for now.
if true
% code
A = [1 1 1 2 2 2 3 4 5 6 6 6 7 8 9 10]; % Matrix that tells from which day data point of B is
B = rand(1,16).*100; % random data times 100 to get bigger numbers
i = 1; % variable used in the while loop
j = 1; % variable used in the while loop
C = []; % new matrix to store the summed data points for each day (it should become a 1x10 matrix in this specific case
while A(i) == i
while A(i) == i
C(1,i) = C(1,i) + B(1,j)
j = j + 1;
end
i = i + 1;
end
end
Hoping to find an answer. - Philipp
0 comentarios
Respuesta aceptada
Stephen23
el 11 de Mayo de 2018
Editada: Stephen23
el 11 de Mayo de 2018
>> A = [1 1 1 2 2 2 3 4 5 6 6 6 7 8 9 10];
>> B = rand(1,16);
>> C = accumarray(A(:),B(:))
C =
1.090191
1.127991
0.044079
0.483190
0.890956
0.136439
0.025175
0.364094
0.165231
0.917592
>> size(C)
ans =
10 1
For MATLAB releases >= R2015b you could use splitapply.
Más respuestas (2)
Cathal Cunningham
el 11 de Mayo de 2018
Use logical indexing to do this
% Pre-build array
C = zeros(1,size(unique(A),2));
for i = 1:length(C)
C(i) = sum(B(A==i));
end
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!