Reputation: 1
So I have a 1x348 cell composed of numbers and empty brackets. Ie ... [] [] [] [169] [170] [170] [170] [171] [172] [] []... All what I want to do is change the repeated numbers to empty brackets []. 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 :-)
Upvotes: 0
Views: 92
Reputation: 32930
Alternatively, you could use NaN
values to represent cells with empty matrices, and vectorize your code:
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)) = {[]};
Upvotes: 1
Reputation: 51470
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 =).
Upvotes: 2
Reputation: 36710
Lets assume you have {1,1,1}
. First iteration will change this to {1,[],1}
and second iteration does not see any repetition. 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,[],[]}
Upvotes: 2