从单元格数组中删除不同数据类型的重复值 [英] Delete repeated values of different data types from cell array
问题描述
我有一个包含许多重复值的单元格列表,其中包括字符串,采样时间,饱和度上限和下限.
I have a list of cell array with many repeated values, which includes strings, sample time, saturation upper limit and lower limit.
例如:
MyValues={ 'Lookc_at_the_stars'
'Lookc_how_they_shine'
'forc_you'
'andm_everything_they_do'
'Theym_were_all_yellow'
'COLDPLAY_STOP'
'COLDPLAY_PLAY'
'COLDPLAY_PLAY'
'COLDPLAY_PLAY'
'COLDPLAY_BREAK'
'COLDPLAY_BREAK'
'Lookc_How_they_shinefor_you'
'its_true'
'COLDPLAY_STOP'
'COLDPLAY_STOP' }
我需要的输出是:
NewMyValues = { 'Lookc_at_the_stars'
'Lookc_how_they_shine'
'forc_you'
'andm_everything_they_do'
'Theym_were_all_yellow'
'COLDPLAY_STOP'
'COLDPLAY_PLAY'
'COLDPLAY_BREAK'
'Lookc_How_they_shinefor_you'
'its_true' }
由于我尝试使用功能unique
,所以无法获取输出,因为它给了我一个错误,说
Since I have tried using the function unique
, I am not able to get the output as it's giving me an error, saying
使用单元格/唯一性时出错
输入A必须是字符串的单元格数组."
"Error using cell/unique
Input A must be a cell array of strings."
MyValues
由不同类型的数据类型值组成.
MyValues
consists of different types of data type values.
有人可以为我提供解决方案或功能代码,以消除重复的值吗?
Can someone provide me a solution or function code, that I could remove the repeated values?
推荐答案
这是一个基于循环的解决方案,用于提取不同类型的单元格数组的唯一值:
Here is a loop based solution to extract unique values of a cell array will different types:
MyValues={ 'Lookc_at_the_stars',
'Lookc_how_they_shine',
1,
'forc_you',
'andm_everything_they_do',
'Theym_were_all_yellow',
2,
'COLDPLAY_STOP',
'COLDPLAY_PLAY',
1,
'COLDPLAY_PLAY',
'COLDPLAY_PLAY',
{1 2 3},
'COLDPLAY_BREAK',
{4 3 5},
'COLDPLAY_BREAK',
{1 2 3},
'Lookc_How_they_shinefor_you',
'its_true',
'COLDPLAY_STOP',
'COLDPLAY_STOP' };
N = numel(MyValues);
idx = true(N,1);
for m = 1: N
if idx(m)
for n = (m+1):N
if idx(n) && isequal(MyValues{m}, MyValues{n})
idx(n) = false;
end
end
end
end
result = MyValues(idx);
结果:
result =
{
[1,1] = Lookc_at_the_stars
[1,2] = Lookc_how_they_shine
[1,3] = 1
[1,4] = forc_you
[1,5] = andm_everything_they_do
[1,6] = Theym_were_all_yellow
[1,7] = 2
[1,8] = COLDPLAY_STOP
[1,9] = COLDPLAY_PLAY
[1,10] =
{
[1,1] = 1
[1,2] = 2
[1,3] = 3
}
[1,11] = COLDPLAY_BREAK
[1,12] =
{
[1,1] = 4
[1,2] = 3
[1,3] = 5
}
[1,13] = Lookc_How_they_shinefor_you
[1,14] = its_true
}
函数isequal
可以使用所有比较的值进行比较,并删除重复项.因此result
是包含唯一值的单元格数组.
根据问题中的示例,是否要具有唯一的字符单元格数组,可以将cellfun
和ischar
一起使用,以检查单元格值是否为字符数组.然后使用逻辑索引提取它们并应用unique
.
The function isequal
can compare anything using it all values compared and duplicates removed. so result
is a cell array that contains unique values.
Based on the example in the question if you want to have unique cell array of characters you can use cellfun
with ischar
to check if the cell value is a character array. Then use the logical index to extract them and apply unique
.
unique(MyValues(cellfun(@ischar,MyValues)),'stable')
不使用stable
选项将对结果进行排序
without using stable
option the result will be sorted
这篇关于从单元格数组中删除不同数据类型的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!