简体   繁体   中英

Any build-in function in MATLAB that can work like `ave` in R?

I am looking for a build-in function in MATLAB which can work in a similar way with ave in R .


Here is an example with R :

set.seed(0)
x <- sample(c("A", "B"), 10, replace = TRUE)
xid <- ave(seq_along(x), x, FUN = seq_along)

which gives

> x
 [1] "B" "A" "B" "A" "A" "B" "A" "A" "A" "B"
> xid
 [1] 1 1 2 2 3 3 4 5 6 4

In other words, I have no idea which function in MATLAB allows me group by x and assign the sequence ids by groups, such that I can get an array like xid . I know splitgroup might be close to the goal, but it doesn't give me the desired output since it yields summarized results.

The question asks to replace each entry in x by the number of times it has occurred so far.

I don't know of a built-in function that does this. Here are some approaches. Let

x = ['B' 'A' 'B' 'A' 'A' 'B' 'A' 'A' 'A' 'B']; % example data. Row vector
  • Short code, but memory-inefficient (computes an intermediate N × N matrix, where N is the length of x ):

     xid = sum(triu(x==x.'));
  • A little more efficient (computes an intermediate U × N matrix, where U is the number of unique elements of x ):

     t = x==unique(x).'; xid = nonzeros(t.*cumsum(t,2)).';
  • Boring efficient code with a loop:

     xid = NaN(size(x)); % preallocate for u = unique(x) t = x==u; xid(t) = 1:sum(t); end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM