user2747063
user2747063

Reputation: 31

matrix containing number of occurrence corresponding to each element in the matrix

I have matrix, suppose

A = [1 2 3 1 1 1 2 3]

I want to find number of times the number appeared in the matrix. The output matrix for this i/p would be

B = [1 1 1 2 3 4 2 2]

i.e. 1 appeared 4 times in the array, hence last value corresponding to 1 is 4.

unique and sum unique do not help because it gives total number of times the element occured, but I want another matrix which increases the count every time it occurs.

Upvotes: 3

Views: 169

Answers (4)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

Here is a solution in MATLAB:

B = sum(triu(bsxfun(@eq, A, A.')));

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

For Matlab:

B = sum(tril(repmat(A,length(A),1)).' + tril(repmat(NaN,length(A),length(A)),-1) == repmat(A,length(A),1))

If A is guaranteed not to contain zeros, this can be simplified to:

B = sum(tril(repmat(A,length(A),1)).' == repmat(A,length(A),1));

Upvotes: 0

MZimmerman6
MZimmerman6

Reputation: 8593

You can do this pretty simply with the following code. This will assume that the A matrix is one dimensional, but this is not too big of an assumption to make.

A=[1 2 3 1 1 1 2 3];
vals = unique(A);
B = zeros(size(A));
for i = 1:numel(vals)
   idxs = find(diff([0,cumsum(A == vals(i))]));
   B(idxs) = 1:numel(idxs);
end

This solution is for MATLAB, not R. I do not know which one you want. If you want an R answer, I would recommend one of the other people's answer :)

Upvotes: 1

amit
amit

Reputation: 3462

try this:

B = ave(A,A,FUN=function(x) 1:length(x))

Upvotes: 1

Related Questions