char array to cell array convert?

조회 수: 6 (최근 30일)
Divyesh pandav
Divyesh pandav 2021년 10월 27일
댓글: Divyesh pandav 2021년 10월 30일
T cell array
T = {[5.8882656], [0.01232356], [0.02556545],[0.035659595] , ...}
A = num2str(T,'%.2f');
A = '5.88 0.01 0.02 0.03 0.04 0.05'
A = str2num(A)
A = NaN
OUTPUT I WANT
A = { 5.88] ,[0.01],[0.02],[0.03],[0.04] , [0.05] }
  댓글 수: 2
Johan
Johan 2021년 10월 27일
T = {[5.8882656], [0.01232356], [0.02556545],[0.035659595]}
T = 1×4 cell array
{[5.8883]} {[0.0123]} {[0.0256]} {[0.0357]}
A = cellfun(@(x) str2num(num2str(x,'%.2f')), T)
A = 1×4
5.8900 0.0100 0.0300 0.0400
Rik
Rik 2021년 10월 27일
@Johan Pelloux-Prayer This looks like an answer. Please move it to the answer section.
A few notes: using cellfun is simply hiding the for loop (which is generally faster). You are also using str2num instead of str2double. str2num calls eval internally and can do a lot of damage if used with untrusted input. str2double has as downside that it will only works on scalars, but is otherwise completely safe to use (it will return NaN if it fails).

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

채택된 답변

Rik
Rik 2021년 10월 27일
If you want to round your data, just use round:
T = {[5.8882656], [0.01232356], [0.02556545],[0.035659595]};
T = cell2mat(T);
T = round(T,2);
T = num2cell(T)
T = 1×4 cell array
{[5.8900]} {[0.0100]} {[0.0300]} {[0.0400]}
You can ignore the trailing zeros when this data is displayed. You should distinguish the data itself and the way it is displayed in Matlab.
  댓글 수: 3
Rik
Rik 2021년 10월 27일
What I mean by that is that it looks as if the numbers have 4 decimals, while we just rounded them to 2. The reality is that we rounded the values to the closest equivalent that can be represented in the internal binary storage system that Matlab uses.
When you see the output in the command window (or here just below the code), that internal representation is translated to a human readable form again.
Divyesh pandav
Divyesh pandav 2021년 10월 30일
@Rik Got it..!!
Thank you

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

추가 답변 (0개)

카테고리

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