简体   繁体   English

用空[]替换单元格的重复值-MATLAB

[英]Replacing repeated values of cell with empty [] - MATLAB

So I have a 1x348 cell composed of numbers and empty brackets. 所以我有一个1x348单元,由数字和空括号组成。 Ie ... [] [] [] [169] [170] [170] [170] [171] [172] [] []... All what I want to do is change the repeated numbers to empty brackets []. 即... [] [] [] [169] [170] [170] [170] [171] [172] [] [] ...我要做的就是将重复的数字更改为空括号[ ]。 I need to hold the places. 我需要保留这些地方。 I tried this, but am not having any success. 我试过了,但没有成功。 It is also not ideal, because in the case with more than one repeat, it would just replace every other repeat with []. 这也不是理想的,因为在重复不止一个的情况下,它将用[]替换所有其他重复。

for jj = 1:length(testcell);
    if testcell{jj} == testcell{jj-1}
        testcell{jj} = []
    end

Any help would be greatly appreciated :-) 任何帮助将不胜感激 :-)

The only thing your code lacks is some variable to store current value: 您的代码唯一缺少的是一些用于存储当前值的变量:

current = testcell{1};
for jj = 2:length(testcell)
    if testcell{jj} == current
        testcell{jj} = [];
    else
        current = testcell{jj};
    end
end

But it's better to use Daniel's solution =). 但是最好使用Daniel的解决方案 =)。

Lets assume you have {1,1,1} . 假设您有{1,1,1} First iteration will change this to {1,[],1} and second iteration does not see any repetition. 第一次迭代会将其更改为{1,[],1} ,第二次迭代看不到任何重复。 Thus iterating backwards is probably the easiest solution: 因此,向后迭代可能是最简单的解决方案:

for jj = length(testcell):-1:2
    if testcell{jj} == testcell{jj-1}
        testcell{jj} = [];
    end
end

Then the first step will result in {1,1,[]} and the second in {1,[],[]} 然后第一步将生成{1,1,[]} ,第二步将生成{1,[],[]}

Alternatively, you could use NaN values to represent cells with empty matrices, and vectorize your code: 另外,您可以使用NaN值来表示具有空矩阵的单元格,并将代码向量化:

testcell(cellfun('isempty', testcell)) = {NaN};
[U, iu] = unique([testcell{end:-1:1}]);
testcell(setdiff(1:numel(testcell), numel(testcell) - iu + 1)) = {NaN};
testcell(cellfun(@isnan, testcell)) = {[]};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM