converting cell of strings in arry or cell of numbers

조회 수: 5 (최근 30일)
Syed Zohaib Ali
Syed Zohaib Ali 2011년 12월 28일
댓글: Oli Fairfax 2021년 4월 1일
I have a cell of strings 'tsince' having dimension 143 by 1 as '4632' '0.00000000' '-1440.00000000' '-1438.00000000' '-1436.00000000' '-1434.00000000' '-1432.00000000' '-1430.00000000' '-1428.00000000' . . . . '1436.00000000' '1438.00000000' '1440.00000000'
I want to convert it to an array or cell of numbers. I tried with str2num() but it gives the following error:
>> tsince2=str2num(tsince) ??? Error using ==> str2num at 33 Requires string or character array input.
I am new to matlab. somebody can please help out how to do this. Thanks in advance
Zohaib

채택된 답변

Jan
Jan 2011년 12월 28일
A surprisingly efficient method even for very large input:
C = {'4632', '0.00000000', '-1440.00000000', '-1438.00000000', ...
'-1436.00000000', '-1434.00000000', '-1432.00000000' '-1430.00000000', ...
'-1428.00000000', '1436.00000000', '1438.00000000', '1440.00000000'};
S = sprintf('%s ', C{:});
D = sscanf(S, '%f');
  댓글 수: 5
Josh Philipson
Josh Philipson 2021년 3월 30일
clever. Thanks Jan!
Oli Fairfax
Oli Fairfax 2021년 4월 1일
I had to make my cell array a single column then ensure empties were converted to NaN (otherwise they got lost) but this worked MUCH quicker than str2double for my example, thanks Jan!
C2 = reshape(C,[],1);
C2(cellfun(@isempty,C2)) = {'NaN'};
S = sprintf('%s ', C2{:});
D = sscanf(S, '%f');
Data = reshape(D, [], size(C,2));

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

추가 답변 (3개)

Nirmal Gunaseelan
Nirmal Gunaseelan 2011년 12월 28일
STR2NUM requires a single string to work on. You need to loop around the individual cell elements and use STR2NUM. CELLFUN is a better way of doing the same - check out the doc.

Matt Tearle
Matt Tearle 2011년 12월 28일
Try str2double(tsince)

Dao Austin
Dao Austin 2015년 4월 17일
you may convert cell to char, then use str2num:
%given A;
C=char(A);
D=str2num(C);

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by