From: leo nidas on 4 Jun 2010 12:10 Hi there, I want to do something simple but turned out to be a headache for me. I have the array for example a=[2 5 5 8 8 8 9 16 16 20]; I want to come up with array b=[1 2 2 3 3 3 4 5 5 6]; I think it is clear. Array a will always be sorted with positive integers. Array b will be sorted too,with positive integers, but the maximum difference will be 1. Array b will always begin from 1. I tried working with an if inside a for and the diff function but I failed big time, I assume that a simpler way may exist. Thanx in advance for any anwers!
From: Jeremy on 4 Jun 2010 12:28 This should do it: a=[2 5 5 8 8 8 9 16 16 20]; index = 1; b(1) = 1; for i = 2:size(a,2) if a(i) ~= a(i-1) index = index + 1; b(i) = index; else b(i) = index; end end
From: dpb on 4 Jun 2010 12:31 leo nidas wrote: > > Hi there, > > I want to do something simple but turned out to be a headache for me. > > I have the array for example a=[2 5 5 8 8 8 9 16 16 20]; > I want to come up with array b=[1 2 2 3 3 3 4 5 5 6]; > > I think it is clear. Array a will always be sorted with positive > integers. Array b will be sorted too,with positive integers, but the > maximum difference will be 1. Array b will always begin from 1. > > I tried working with an if inside a for and the diff function but I > failed big time, I assume that a simpler way may exist. .... >> u=unique(a); >> [n,bin]=histc(a,u) n = 1 2 3 1 2 1 bin = 1 2 2 3 3 3 4 5 5 6 >> --
From: Doug Schwarz on 4 Jun 2010 13:17 leo nidas wrote: > > I have the array for example a=[2 5 5 8 8 8 9 16 16 20]; > I want to come up with array b=[1 2 2 3 3 3 4 5 5 6]; [unused,unused,b] = unique(a); -- Doug Schwarz dmschwarz&ieee,org Make obvious changes to get real email address.
From: Bruno Luong on 4 Jun 2010 13:42 HISTC, UNIQUE solutions will call for some kind of sorting, which can be penalizing for large array. Jeremy's for-loop solution has better theoretical complexity, but it's not vectorized. Another solution is: b = cumsum([1 diff(a)>0]) Bruno
|
Next
|
Last
Pages: 1 2 Prev: Problem about controlling Pan and tilt of Logitech Orbit webcam Next: adjecent |