How delete duplicate strings in cell array

I have a matrix with some cell arrays of chars representing numbers and I need to eliminate duplicate elements of each columns. I tried using unique but when I have elements with diferents lengths unique do not solve the problem.
My data is :
M= {'100' '500' '2 3 4' '50000'; '100' '500' '2' '0';'100' '500' '3' '0';'100' '500' '4' '0';'100' '500' '2 3 4' '20000'};
M = 5x4 cell of chars
unique(M(:,1)) %gives me '100'
unique(M(:,2)) %gives me '500'
both are corrects but
unique(M(:,3)) %gives me '2' '2 3 4' '3' '4'
unique(M(:,4)) %gives me '0' '0 20000' '20000' '50000'
and I need only one result: '2 3 4' for column 3 and '0 20000 50000' for column 4
Matrix M is size N x 4
The result I need is R = {'100' '500' '2 3 4' '0 20000 50000' }
My code is strange and I need a more nice solution, I am using Matlab version 2017b.
for i=1:4
mm = M(:,i);
tmp=unique(mm);
if size(tmp,1) == 1
R{i} = char(tmp);
else
R{i}=char(cellstr(strjoin(unique(split(string(strjoin(mm,' ')))))));
end
end

 Akzeptierte Antwort

Stephen23
Stephen23 am 7 Jun. 2020
Bearbeitet: Stephen23 am 8 Jun. 2020

0 Stimmen

You could easily hide the loop inside cellfun, e.g.:
>> fun = @(c)sprintf(' %u',unique(sscanf(sprintf(' %s',c{:}),'%f')));
>> out = cellfun(fun,num2cell(M,1),'uni',0)
out =
' 100' ' 500' ' 2 3 4' ' 0 20000 50000'
Of course with R2017b you can probably replace the outer sprintf with strjoin.

2 Kommentare

Marcelo
Marcelo am 8 Jun. 2020
It works, but how to replace fun with strjoin?
Stephen23
Stephen23 am 8 Jun. 2020
Bearbeitet: Stephen23 am 8 Jun. 2020
"but how to replace fun with strjoin?"
I don't think that it is possible to replace the entire function with one strjoin call.
But you might be able to replace the outer sprintf with strjoin, as I wrote. Try it.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 7 Jun. 2020

Bearbeitet:

am 8 Jun. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by