Using cellfun to extract numbers from strings in a cell array
    2 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
    KostasK
      
 am 4 Nov. 2021
  
    
    
    
    
    Beantwortet: Yongjian Feng
    
 am 4 Nov. 2021
            Hi all, 
I currently have the following code which extracts numbers from strings found within a cell array. 
Cel = {'1-2-3-4-5-6' '5-6-7-8'} ;
fun = @(X) cellfun(@(C) abs(sscanf(C,'%d')), X, 'Un', 0) ;
xx = fun(Cel)
This works great. But my problem is that I have a case in my cell array with empty cells, like so:
Cel = {'1-2-3-4-5-6' '5-6-7-8' [] []} ;
fun = @(X) cellfun(@(C) abs(sscanf(C,'%d')), X, 'Un', 0) ;
xx = fun(Cel)
I would like for the code to return xx = {[1 2 3 4 5 6] [5 6 7 8] [] []}, but obviously since my function does not work with empty cells, I get an error. 
So I would like to know what alternatives do I have such that I can accomplish the above?
0 Kommentare
Akzeptierte Antwort
  Yongjian Feng
    
 am 4 Nov. 2021
        How about this:
Cel = {'1-2-3-4-5-6' '5-6-7-8' [] []} ;
xx = cellfun(@(x) foo(x), Cel, 'Un', 0);
function ret = foo(x)
    ret = [];
    if ~isempty(x)
        ret = abs(sscanf(x, "%d"));
    end
end
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
				Mehr zu Cell 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!

