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 views (last 30 days)
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!

Accepted Answer

the cyclist
the cyclist on 22 Jan 2018
% 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 Comments
the cyclist
the cyclist on 22 Jan 2018
Edited: the cyclist on 22 Jan 2018
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!