how to add and sort a cell with a string in a cell array in order to replace or add a cell with respect the last word of the cell?

2 次查看(过去 30 天)
I did this using a lot of lines and I was wondering if you could recommend me a better way to do it.
I have a predefined cell array and I'm constantly generating new data that I have to add or replace in the cell array and sorted regarding the last word of the cell.
Let's say I have a cell array A like:
A{1, 1} = 'whatever - a';
A{2, 1} = 'doesNotMatter - b';
A{3, 1} = 'not even with spaces - d';
A{4, 1} = 'blablabla - ee';
if I have these new cells to add in my array
newCell1 = 'thanksForHelping - c';
newCell2 = 'I really appreciate it - ee';
I would like to add newCell1 (since "c" is not in the original) and replace newCell2 with the one in A{4, 1} (since "ee" is there)
so at the end, I can obtain something like:
A =
5×1 cell array
'whatever - a'
'doesNotMatter - b'
'thanksForHelping - c'
'not even with spaces - d'
'I really appreciate it - ee'
I know that the ideal thing will be to change the data to "a - whatever" and use a simple sort but it is not possible to change the final format.
Could you recommend me something?
Thanks!

采纳的回答

the cyclist
the cyclist 2018-1-22
% The data
A{1, 1} = 'whatever - a';
A{2, 1} = 'doesNotMatter - b';
A{3, 1} = 'not even with spaces - d';
A{4, 1} = 'blablabla - ee';
newCell{1,1} = 'thanksForHelping - c';
newCell{2,1} = 'I really appreciate it - ee';
% Find last words in the old and new data
hyphenIndexA = regexp(A,'-');
lastWordA = cellfun(@(x,y)x(y+2:end),A,hyphenIndexA,'UniformOutput',false);
hyphenIndexNew = regexp(newCell,'-');
lastWordNew = cellfun(@(x,y)x(y+2:end),newCell,hyphenIndexNew,'UniformOutput',false);
% Swap in the replacements if they exist
[tfReplace,locationIndexReplace] = ismember(lastWordA,lastWordNew);
A(tfReplace) = newCell(locationIndexReplace(tfReplace));
% Append the new to the old, if they do not exist
[tfAdd,locationIndexAdd] = ismember(lastWordNew,lastWordA);
A = [A; newCell(not(tfAdd))]
  3 个评论
the cyclist
the cyclist 2018-1-22
编辑:the cyclist 2018-1-22
Be sure to do that step after you've got the new elements and replacements in there.
There might be a more efficient way to combine some of those steps, I suppose. But better to understand the whole algorithm first.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by