convert cell array of mixed strings to cell array of numbers
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have a cell array as follows:
ca = [{' [1000 X X X X]' } {' X' } {' X' } {' 1.234' }];
I would like to convert this into a numeric cell array where 'X' is interperted as 'NaN'. My solution uses the following function:
function out = x2decimal(in)
%sscanf doesn't handle NaN
X = NaN;
out = eval(in);
return
In cellfun:
out = cellfun(@(x) x2decimal(x), ca, 'Uni', false)
out = {1×5 double} {[NaN]} {[NaN]} {[1.2340]}
out{1} = 1000 NaN NaN NaN NaN
My solution works but contains the dreaded eval function. Do you see an alternative that is more mat-thonic?
On windows 10, matlab 2020b.
Thanks,
-Chris
2 Kommentare
Dyuman Joshi
am 8 Feb. 2023
Not sure about mat-thonic, but here is another approach -
ca = [{' [1000 X X X X]' } {' X' } {' X' } {' 1.234' }];
ca = replace(ca,'X', 'NaN');
out = cellfun(@str2num, ca, 'uni', 0)
Antworten (1)
Stephen23
am 9 Feb. 2023
Bearbeitet: Stephen23
am 9 Feb. 2023
ca = {' [1000 X X X X]', ' X', ' X', ' 1.234' }
out = regexp(ca,'[^\s\[\]]+','match');
out = cellfun(@str2double,out,'uni',0)
2 Kommentare
Dyuman Joshi
am 9 Feb. 2023
So the approach above is to divide each element into cell arrays and then use str2double?
Stephen23
am 9 Feb. 2023
"So the approach above is to divide each element into cell arrays and then use str2double?"
Yes.
Siehe auch
Kategorien
Mehr zu Data Type Conversion 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!