Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

Repeat copies of array elements: Run-length decoding in MATLAB

I'm trying to insert multiple values into an array using a 'values' array and a 'counter' array. For example, if:

a=[1,3,2,5]
b=[2,2,1,3]

I want the output of some function

c=somefunction(a,b)

to be

c=[1,1,3,3,2,5,5,5]

Where a(1) recurs b(1) number of times, a(2) recurs b(2) times, etc...

Is there a built-in function in MATLAB that does this? I'd like to avoid using a for loop if possible. I've tried variations of 'repmat()' and 'kron()' to no avail.

This is basically Run-length encoding.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Benchmarks

Updated for R2015b: repelem now fastest for all data sizes.


Tested functions:

  1. MATLAB's built-in repelem function that was added in R2015a
  2. gnovice's cumsum solution (rld_cumsum)
  3. Divakar's cumsum+diff solution (rld_cumsum_diff)
  4. knedlsepp's accumarray solution (knedlsepp5cumsumaccumarray) from this post
  5. Naive loop-based implementation (naive_jit_test.m) to test the just-in-time compiler

Results of test_rld.m on R2015b:

repelem time

Old timing plot using R2015a here.

Findings:

  • repelem is always the fastest by roughly a factor of 2.
  • rld_cumsum_diff is consistently faster than rld_cumsum.
  • repelem is fastest for small data sizes (less than about 300-500 elements)
  • rld_cumsum_diff becomes significantly faster than repelem around 5 000 elements
  • repelem becomes slower than rld_cumsum somewhere between 30 000 and 300 000 elements
  • rld_cumsum has roughly the same performance as knedlsepp5cumsumaccumarray
  • naive_jit_test.m has nearly constant speed and on par with rld_cumsum and knedlsepp5cumsumaccumarray for smaller sizes, a little faster for large sizes

enter image description here

Old rate plot using R2015a here.

Conclusion

Use repelem below about 5 000 elements and the cumsum+diff solution above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...