How to count sum for values corresponding to repeated numbers in matrixes.

3 visualizaciones (últimos 30 días)
Dear experts,
I have a 2 column ascii file with numbers as it looks at the first 2 columns from the left.
Shortly:
EventID Hits Sum
----------------------------
9170 1 1
9443 2 14
9443 4 14
9443 8 14
15872 4 12
15872 8 12
16077 4 12
16077 8 12
22374 1 1
23801 4 12
How I could get the 3rd column as a product? For example, the number 9443 is repeated 3 times and I would like to place the sum 2+4+8=14 on the place fo 9443 etc
I tried by counting unique numbers like:
fid = fopen('200Mevents_file4_geant.txt', 'r');
data = fscanf(fid, '%f');
nRows = data(1);
data = reshape(data(1:end), 106695, 1).';
c = unique(data);
for i = 1:length(data)
counts(i,1) = sum(data==data(i)); % number of times each unique value is repeated
end
Could you help me?
Georgios

Respuesta aceptada

KSSV
KSSV el 23 de Feb. de 2021
Editada: KSSV el 23 de Feb. de 2021
clc; clear all ;
data = [9170 1 1
9443 2 14
9443 4 14
9443 8 14
15872 4 12
15872 8 12
16077 4 12
16077 8 12
22374 1 1
23801 4 12] ;
[c,ia,ib] = unique(data(:,1)) ;
n = length(c) ;
iwant = zeros(n,3) ;
for i = 1:n
iwant(i,:) = [c(i) sum(data(ib==i,2)) data(ia(i),3)] ;
end
  3 comentarios
Georgios Tsiledakis
Georgios Tsiledakis el 23 de Feb. de 2021
Hi,
Sorry for botherig again but unfortunately it is not correct yet.
I run the updated code and the product is iwant is 6x3 instead of 10x1.
9170 1 1
9443 14 14
15872 12 12
16077 12 12
22374 1 1
23801 4 12
I would like to have as a result the 3rd colum of the 10x3 array.
Thus,
1
14
14
14
12
12
12
12
1
12
12
2
I also forgot 2 more elements in the 3x12 array.
Here is the right one:
9170 1 1
9443 2 14
9443 4 14
9443 8 14
15872 4 12
15872 8 12
16077 4 12
16077 8 12
22374 1 1
23801 4 12
23801 8 12
23804 2 2

Iniciar sesión para comentar.

Más respuestas (1)

Georgios Tsiledakis
Georgios Tsiledakis el 26 de Feb. de 2021
Hello,
I manage to get what I wanted thanks to your help.
I provide the code below.
load data.dat
[c,ia,ib] = unique(data(:,1)) ;
n = length(c) ;
n2 = length(data) ;
iwant = zeros(n,1) ;
iwant2 = zeros(n,1) ;
iwant3 = zeros(n,1) ;
%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:n
iwant(i) = sum(data(ib==i,2)) ;
end
%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:length(data)
counts(i,1) = sum(ib==ib(i));
end
%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:n2
iwant2(i) = sum(data(ib==ib(i),2)) ;
end
%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:n2
iwant3(i) = sum(data(ib==i,2)) ;
end

Categorías

Más información sobre Logical 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!

Translated by