MATLAB: How to edit certain cells of a cell-array with a logical index (without using for-loops)

cellcell arraycell arraysismember

Hi everyone,
lets say I have a cell array and a numeric array like:
Old_Array = {20 , '2' ; 21 , '2' ; 22 , '2,3' ; 25 , '3' ; 28 , '2'};
and
new_Numbers = [18 ; 21 ; 22 ; 32];
What I want, is to some kind of mix those two. If a number of new_Numbers matches with the first column of old_Array, i want to add '4' to the cell in the 2nd column on just that row. If a number of new_Numbers is not matched, i want to add it, with the 2nd column containing the'4' String. The result should look like
New_Array = {18 , '4' ; 20 , '2' ; 21 , '2,4' ; 22 , '2,3,4' ; 25 , '3' ; 28 , '2' ; 32 , '4'};
I wonder if there is a solution not using for loops but [i,j]=ismember(new_Numbers,cell2mat(Old_Array(:,1))) and the logical indexes.
Thanks in advance. Any Help is appreciated! 🙂

Best Answer

This is fairly inelegant, but it is a vectorized solution:
Old_Array = {20 , '2' ;
21 , '2' ;
22 , '2,3' ;
25 , '3' ;
28 , '2'};
new_Numbers = [18 ; 21 ; 22 ; 32];
% Find which numbers are really new
[tr,loc] = ismember(new_Numbers,cell2mat(Old_Array(:,1)));
% Initialize new array as a copy
New_Array = Old_Array;
% Append ',4' to rows that match
New_Array(loc(tr),2) = cellfun(@(x)[x,',4'],New_Array(loc(tr),2),'UniformOutput',false)
% Add new numbers that don't appear in old
Number_New_Numbers = sum(not(tr));
New_Block = [num2cell(new_Numbers(not(tr))),repmat({'4'},Number_New_Numbers,1)]
New_Array = [New_Array; New_Block]
% Sort the new array
[~,sortingIndex] = sort([New_Array{:,1}]')
New_Array = New_Array(sortingIndex,:)