Need help inproveing function...
이전 댓글 표시
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!
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!