Removing adjacent duplicate numbers in rows of a matrix

2 ビュー (過去 30 日間)
AA
AA 2019 年 6 月 21 日
コメント済み: infinity 2019 年 6 月 23 日
Hi,
assume the following matrix format:
xx=[1 2 3 3 4 4; 1 1 2 2 3 3 ; 5 5 5 3 3 2]
I want to remove the adjacent duplicate numbers in each row of this matrix so I get the following output:
result=[1 2 3 4; 1 2 3 ; 5 3 2]
Help would be very much appreciated with a formula. Thanks.

回答 (2 件)

infinity
infinity 2019 年 6 月 21 日
Hello,
In your problem, you may get error since your result is not a matrix (number of colume of the first row is different with other rows).
So, you result should be a cell like this
clear
xx=[1 2 3 3 4 4; 1 1 2 2 3 3 ; 5 5 5 3 3 2]
for i = 1:size(xx,1)
yy{i} = unique(xx(i,:));
end
  12 件のコメント
AA
AA 2019 年 6 月 22 日
編集済み: AA 2019 年 6 月 22 日
Hi,
somehow I see an error when I modify the xx and increase the set of numbers. Adjacent numbers can repeat like 3 or 2 or 5 but they are not displayed in the output.
clear
xx=[1 2 3 3 4 4 3; 1 1 2 2 3 3 2; 5 5 5 3 3 2 5]
%yy = zeros(size(xx));
yy=NaN(size(xx))
for row = 1:size(xx,1)
temp = unique(xx(row,:),'stable');
yy(row,1:length(temp)) = temp;
end
The last digit 3 or 2 or 5 is not shown in the output. Instead i get
1 2 3 4 NaN NaN NaN
1 2 3 NaN NaN NaN NaN
5 3 2 NaN NaN NaN NaN
but I should get
1 2 3 4 3 NaN NaN
1 2 3 2 NaN NaN NaN
5 3 2 5 NaN NaN NaN
How can I modify the formula?
infinity
infinity 2019 年 6 月 23 日
Hello,
You can modify the code like this
clear
% xx=[1 2 3 3 4 4; 1 1 2 2 3 3 ; 5 5 5 3 3 2]
% xx=[1 2 3 3 4 4; 1 1 2 2 3 3 ; 5 4 5 3 3 2]
xx=[1 2 3 3 4 4 3; 1 1 2 2 3 3 2; 5 5 5 3 3 2 5]
% xx=[1 2 3 3 4 4 3 3; 1 1 2 2 3 3 2 3; 5 5 5 3 3 2 5 5]
n = size(xx,2);
% yy = 0*xx;
yy=NaN(size(xx));
for i = 1:size(xx,1)
[temp,ia,ib] = unique(xx(i,:),'stable');
f = diff(ib)~=0;
idx = [find(f);length(ib)];
% yy(i,1:length(temp)) = temp;
yy(i,1:length(idx)) = xx(i,idx);
end
yy

サインインしてコメントする。


Rik
Rik 2019 年 6 月 22 日
You can use diff to find any repeats and remove them. The compare to eps is to avoid strange things happening once you put in decimal numbers, which can lead to rounding errors, which is why exp(log(3))==3 returns false.
xx=[1 2 3 3 4 4 3; 1 1 2 2 3 3 2; 5 5 5 3 3 2 5];
yy=NaN(size(xx));
for row = 1:size(xx,1)
temp = xx(row,:);
%keep values that are different from the one before
%L=[true diff(temp)~=0];%line below is safe for float rounding
L=[true abs(diff(temp))>=(2*eps)];
yy(row,1:sum(L)) = temp(L);
end
%remove trailing NaN cols:
while all(isnan(yy(:,end)))
yy(:,end)=[];
end
disp(yy)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by