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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
German Preciat Gonzalez
am 22 Jan. 2018
Bearbeitet: the cyclist
am 22 Jan. 2018
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!
0 Kommentare
Akzeptierte Antwort
the cyclist
am 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 Kommentare
the cyclist
am 22 Jan. 2018
[sortedLastWordA,sortingIndex] = sort(lastWordA);
A = A(sortingIndex);
the cyclist
am 22 Jan. 2018
Bearbeitet: the cyclist
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!