Clear Filters
Clear Filters

Create a vector with the number of repetitions

1 view (last 30 days)
Hello, I wouldlike to create a vectorwith the number of repititions of a number for example, I have this data:
clear all
clc
data = [ 1 2004 3 5;
2 2004 7 2;
1 2005 9 4;
2 2005 6 5;
3 2005 3 7;
4 2005 8 2] % Where data(:,1) is id and data(:,2) is year.
I would like to create a code that counts the numbers of id per year in a vector, just like this:
result = [2 2 4 4 4 4]';
thank you very much in advance.

Accepted Answer

the cyclist
the cyclist on 5 Feb 2017
Edited: the cyclist on 5 Feb 2017
I feel like there must be a better way, but this will work
data = [ 1 2004 3 5;
2 2004 7 2;
1 2005 9 4;
2 2005 6 5;
3 2005 3 7;
4 2005 8 2 ] % Where data(:,1) is id and data(:,2) is year.
dataYear = data(:,2);
uniqueDataYear = unique(dataYear);
dataYearCount = histcounts(dataYear,[uniqueDataYear; Inf])
[~,loc] = ismember(dataYear,uniqueDataYear);
result = dataYearCount(loc)'

More Answers (0)

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!