How to count number of occurences of each value in a vector and put the number beside the value as a new column?
19 次查看(过去 30 天)
显示 更早的评论
I have vector (3079X1).
I want to count the number of occurrences of each value within the vector and put that number beside the respective value of the vector. I have tried using groupcount but it reorders the result in ascending order. I want to keep the same order as it was in the original vector.
0 个评论
回答(3 个)
Stephen23
2020-4-13
>> V = randi(9,13,1)
V =
6
4
4
2
9
5
1
6
2
1
6
9
4
>> [N,X] = histc(V,unique(V));
>> M = [V,N(X)]
M =
6 3
4 3
4 3
2 2
9 2
5 1
1 2
6 3
2 2
1 2
6 3
9 2
4 3
darova
2020-4-13
Try this
a = randi(5,20,1);
x = a*0;
[a1,ix] = sort(a); % sort array to see how many duplicates
k = 0;
for i = 1:length(a)-1
if a1(i)~=a1(i+1)
x(k+1:i) = i-k; % write numer of duplicates
k = i; % position of last diplicate
end
end
x(k+1:end) = length(x)-k; % write last portion of duplicates
[~,ix1] = sort(ix); % restore original order
disp('sorted values with number of duplicates')
[a1 x]
disp('original values with numer of duplicates')
[a x(ix1)]
2 个评论
Walter Roberson
2020-4-14
You posted that you have a "vector"; it now appears that you have a cell array of some sort. Possibly it is a cell array of character vectors. Possibly it is a cell array of transfer functions. Possibly it is a cell array of function handles. We would need more information to advise you.
Image Analyst
2020-4-13
Try this:
% Create sample data
v = randi(1000, 3079, 1)
% Now take a histogram:
edges = min(v) : 1 : max(v)+1;
hObject = histogram(v, edges) % Also displays the histogram
grid on;
% Create matrix with v as first column, and count as second column
m = [v, zeros(length(v), 1)];
% Assign the counts to each value.
for k = 1 : length(v)
% Get the value of the vector at this index.
value = v(k);
% Get the counts from the histogram for that value
% and stuff into the second column of m.
m(k, 2) = hObject.Values(value);
end
6 个评论
Image Analyst
2020-4-14
I just copied and pasted my code and it ran fine. Moreover, the first argument to min() is a numeric vector -- it's a double. So you must have altered my code somehow. But you forgot to attach your modified script. Please do so if you want me to fix it.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!