Determining the total value of the number in each position of a matrix that corresponds to another same length matrix

Let's say i have a column vector medals = [1;1;5;7;3;1] and i have another column vector year = [2007;2009;2011;2018;2007;2007] and each of the element in 'year' corresponds to the matrix 'medals'. Eg: in 2007,i have 5 medals because year(1) ,year(5) and year(6) are 2007, and the total medals i won is 1+3+1 How do i find the total medals won for each of the year?

 Accepted Answer

>> year = [2007;2009;2011;2018;2007;2007];
>> medals = [1;1;5;7;3;1];
>> [uni,~,idx] = unique(year);
>> cnt = accumarray(idx,medals);
>> [uni,cnt]
ans =
2007 5
2009 1
2011 5
2018 7

6 Comments

You could pass year into accumarray directly, but if you did the output from accumarray would be much longer (2018 elements rather than 4) and most of those elements would be 0.
z = accumarray(year, medals);
[yearsWithMedals, ~, medalsInEachYear] = find(z);
t = table(yearsWithMedals, medalsInEachYear)
Look at the size of z as compared to the size of t.
whos
Can i ask why do i get the correct answer if i put accumarray(idx,1)?
"Can i ask why do i get the correct answer if i put accumarray(idx,1)?"
When I try your suggested code I get a different answer:
>> year = [2007;2009;2011;2018;2007;2007];
>> medals = [1;1;5;7;3;1];
>> [uni,~,idx] = unique(year);
>> cnt = accumarray(idx,medals);
>> [uni,cnt]
ans =
2007 5
2009 1
2011 5
2018 7
>> accumarray(idx,1)
ans =
3
1
1
1
They don't look the same to me. However this is exactly what I would expect accumarray(idx,1) to return: a count of how many times each year occurs in the variable year, just like a histogram.
The question is ‘determine the number of medals won per year’ so did I misunderstood the question or the answer is wrong?
"...so did I misunderstood the question or the answer is wrong?"
Your question gives an example "Eg: in 2007... the total medals i won is 1+3+1", and that is exactly what my code gives you: for 2007 it returns the value 5. The other years seem to be correct too, when I check them. What are you expecting to get?

Sign in to comment.

More Answers (1)

medals = [1;1;5;7;3;1] ;
year = [2007;2009;2011;2018;2007;2007] ;
[c,ia,ib] = unique(year) ;
iwant=sum(medals(ib==1))

Asked:

on 3 May 2018

Edited:

on 6 May 2018

Community Treasure Hunt

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

Start Hunting!