필터 지우기
필터 지우기

convert cell array of mixed strings to cell array of numbers

조회 수: 2 (최근 30일)
checker
checker 2023년 2월 8일
댓글: Stephen23 2023년 2월 9일
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
Dyuman Joshi
Dyuman Joshi 2023년 2월 8일
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)
out = 1×4 cell array
{[1000 NaN NaN NaN NaN]} {[NaN]} {[NaN]} {[1.2340]}
checker
checker 2023년 2월 9일
Thanks, that saves me a custom function. Interestingly, str2num uses eval! I'd use str2double but want to perserve exactly the textual representation of the numbers (which are sourced from a single precision float) and it's not clear to me how str2double would affect the display.

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
Stephen23 2023년 2월 9일
편집: Stephen23 2023년 2월 9일
ca = {' [1000 X X X X]', ' X', ' X', ' 1.234' }
ca = 1×4 cell array
{' [1000 X X X X]'} {' X'} {' X'} {' 1.234'}
out = regexp(ca,'[^\s\[\]]+','match');
out = cellfun(@str2double,out,'uni',0)
out = 1×4 cell array
{[1000 NaN NaN NaN NaN]} {[NaN]} {[NaN]} {[1.2340]}
  댓글 수: 2
Dyuman Joshi
Dyuman Joshi 2023년 2월 9일
So the approach above is to divide each element into cell arrays and then use str2double?
Stephen23
Stephen23 2023년 2월 9일
"So the approach above is to divide each element into cell arrays and then use str2double?"
Yes.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by