How to count number of occurences of each value in a vector and put the number beside the value as a new column?
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
Stephen23
am 13 Apr. 2020
>> 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
am 13 Apr. 2020
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 Kommentare
Walter Roberson
am 14 Apr. 2020
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
am 13 Apr. 2020
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 Kommentare
Image Analyst
am 14 Apr. 2020
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.
Siehe auch
Kategorien
Mehr zu Calendar finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!