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

 Réponse acceptée

Stephen23
Stephen23 le 7 Juin 2020
Modifié(e) : Stephen23 le 8 Juin 2020
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 commentaires

Marcelo
Marcelo le 8 Juin 2020
It works, but how to replace fun with strjoin?
Stephen23
Stephen23 le 8 Juin 2020
Modifié(e) : Stephen23 le 8 Juin 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by