How to convert char data to double format?

조회 수: 20 (최근 30일)
Y Choi
Y Choi 2023년 7월 20일
이동: Stephen23 2023년 7월 21일
Hello!
I have data in the following char format.
The size of the data is [2x72], and I want to store each element, including the spaces,
in a matrix to create a double-format data with the same size.
val = ['11 444 214141111 11111111111114111111111 1111111113111111111 111'
'11 444 214141113 11111311111114111111121 1111111123111111111 111' ]; % char
When I use str2double, it returns NaN.
Could you please tell me how I can save this data?
  댓글 수: 1
Stephen23
Stephen23 2023년 7월 20일
이동: Stephen23 2023년 7월 21일
"The size of the data is [2x72],..."
The data you provided is actually a 2x64 char array.
"I want to store each element, including the spaces, in a matrix to create a double-format data with the same size."
Here it is, guaranteed to be exactly the same size as your character array. But I doubt you will be very happy
val = ['11 444 214141111 11111111111114111111111 1111111113111111111 111';'11 444 214141113 11111311111114111111121 1111111123111111111 111']
val = 2×64 char array
'11 444 214141111 11111111111114111111111 1111111113111111111 111' '11 444 214141113 11111311111114111111121 1111111123111111111 111'
num = double(val)
num = 2×64
49 49 32 52 52 52 32 50 49 52 49 52 49 49 49 49 32 49 49 49 49 49 49 49 49 49 49 49 49 49 49 49 32 52 52 52 32 50 49 52 49 52 49 49 49 51 32 49 49 49 49 49 51 49 49 49 49 49 49 49

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

답변 (1개)

Walter Roberson
Walter Roberson 2023년 7월 20일
format long g
val = ['11 444 214141111 11111111111114111111111 1111111113111111111 111'
'11 444 214141113 11111311111114111111121 1111111123111111111 111' ]; % char
result_double = cell2mat(cellfun(@str2double,regexp(cellstr(val), '\s+', 'split'),'UniformOutput',false))
result_double = 2×6
1.0e+00 * 11 444 214141111 1.11111111111141e+22 1.11111111311111e+18 111 11 444 214141113 1.11113111111141e+22 1.11111112311111e+18 111
%or
result_u64 = cell2mat(cellfun(@(S) sscanf(S, '%ld').', cellstr(val), 'uniform', 0))
result_u64 = 2×6
11 444 214141111 9223372036854775807 1111111113111111111 111 11 444 214141113 9223372036854775807 1111111123111111111 111
However:
  • you cannot include spaces in the numeric array. In order to include spaces, you would need to convert back to character or string() unless what you wanted was a cell array that alternates double and char
  • your values such as 11111311111114111111121 exceed the largest possible integer exactly representable in double precision, and also exceed the largest possible 64 bit integer, so you will not be able to represent the values exactly -- not unless you use symbolic numbers
result_sym = str2sym("[" + cellstr(val) + "]")
result_sym = 

카테고리

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