MATLAB Answers

Need help inproveing function...

1 view (last 30 days)
Chris E.
Chris E. on 29 Jul 2013
Hello Everyone, I have a function that looks at a vector of numbers and will mark any numbers in that vector that repeat with the value they repeat with. I have code that is working, but it is the ugly and really bad programing and I know it. If anyone could help out I would much appreciate it! Here is an example and the code that is bad that I'm using:
x = [1 1 3 5 4 6 6 1 9 1 1 8 2 5 5 5 2 7 7 2 2 2];
out = [2 0 0 0 2 0 0 2 0 0 3 0 2 3]
%So in x (from the beginning):
%there are two 1's that become 2;
%then 3 mismatching values of 3,5, and 4 that become 0, 0, and 0;
%then two 6's that become 2;
%then 2 mismatching values of 1 and 9 that become 0 and 0;
%then two 1's that become 2;
%then 2 mismatching values of 8 and 2 that become 0 and 0;
%then three 5's that become 3;
%then 1 value of 2 (no matching neighbors) that become 0;
%then two 7's that become 2;
%then three 2's that become 3;
%code that works this way:
x = [1 1 3 5 4 6 6 1 9 1 1 8 2 5 5 5 2 7 7 2 2 2];
x = [x 0];
c = 1;
num = x(1);
b = 2;
r = 1;
for n = 2:length(x)
if b >= length(x)
break
end
if x(b) == num
if n == length(x)
break
end
while x(b) == num
if b >= length(x)
r = r + 1;
g(c) = r;
break
end
b = b + 1;
num = x(b - 1);
r = r + 1;
end
g(c) = r;
c = c + 1;
r = 1;
else
while x(b) ~= num
b = b + 1;
num = x(b - 1);
if b >= length(x)
break
end
if x(b) ~= num
g(c) = 0;
c = c + 1;
end
end
end
end
out = g
%output:
out = [2 0 0 0 2 0 0 2 0 0 3 0 2 3]
Well that is the really ugly function, any help with it will be great!
Thanks!

Accepted Answer

Evan
Evan on 29 Jul 2013
Edited: Evan on 29 Jul 2013
Does this do what you want?
>> x = [1 1 3 5 4 6 6 1 9 1 1 8 2 5 5 5 2 7 7 2 2 2];
>> idx = cumsum([1 diff(x) ~= 0]);
>> out = accumarray(idx.',ones(size(idx))).';
>> out(out == 1) = 0;
out =
2 0 0 0 2 0 0 2 0 0 3 0 2 3
For run-length encoding (i.e. what it looks like you're doing here) the cumsum and accumarray functions are very helpful, although they can be tricky to get used to at first.
  2 Comments
Evan
Evan on 29 Jul 2013
No problem! =)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!