Search code examples
arraysstringmatlabcell-array

The use of Cell array of strings in a program


Suppose I have the following code

mc = {[2 5],[2 5],[8 9 2],[33 77 4],[102 6],[110 99],[2 5]}

(Identifying uniques in a cell array:Jonas Answer):

%# convert to strings
mcs = cellfun(@(x)(mat2str(x)),mc,'uniformoutput',false);

%# run unique
[uniqueCells,idxOfUnique,idxYouWant] = unique(mcs);

fileName = ['C:\Users\MATLAB\matrice_Result.mat'];  
save(fileName,'uniqueCells');

to load the result and use it as a cell, Can I do that ?:

load('C:\Users\MATLAB\matrice_Result.mat');
A = uniqueCells;

B = [5 77 41 66 7];

(Finding the vectors of the cell A that contain at least one element of the vector B: Divakar Answer)

R = A(arrayfun(@(n) any(ismember(B,A{n})),1:numel(A)));

I have the impression that the second code does not recognize A !!!


Solution

  • Just use str2num(A{n}) to convert each cell of A back into numeric form:

    R = A(arrayfun(@(n) any(ismember(B,str2num(A{n}))),1:numel(A)));
    

    The above gives the result in string form, because A{n} is converted to numbers within ismember but A is left in string form. If you want the result in numeric form, first convert A and then apply your (Divakar's) original line to the converted A:

    A_num = cellfun(@str2num, A, 'uniformoutput', 0);
    R = A_num(arrayfun(@(n) any(ismember(B,A_num{n})),1:numel(A)));