필터 지우기
필터 지우기

Convert a cell column of strings to doubles

조회 수: 6 (최근 30일)
Eli Dim
Eli Dim 2015년 7월 15일
댓글: Star Strider 2015년 7월 15일
I have a cell column of strings which looks like the attached file. How can I convert the column to double-precision values?
  댓글 수: 1
Stephen23
Stephen23 2015년 7월 15일
Please try attaching your data again. Press then parperclip button, then both the Choose file and Attach file buttons.

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

채택된 답변

Star Strider
Star Strider 2015년 7월 15일
See if this does what you want:
D = load('string_column.mat');
data = D.owner;
out = cellfun(@(x) str2num(char(x)), data);
  댓글 수: 2
Eli Dim
Eli Dim 2015년 7월 15일
Thank you very much, I understand now what the problem was!
Star Strider
Star Strider 2015년 7월 15일
As always, my pleasure!

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

추가 답변 (2개)

Stephen23
Stephen23 2015년 7월 15일
편집: Stephen23 2015년 7월 15일
If the data is a cell array of strings, then try using str2double:
>> A = {'1.2';'2.3';45.6789';'Inf'};
>> B = str2double(A);
B =
1.2000
2.3000
45.6789
Inf
  댓글 수: 3
Guillaume
Guillaume 2015년 7월 15일
편집: Guillaume 2015년 7월 15일
The column consists only of numeric values.
No! All but the last four cells of your cell arrays are actually cell arrays themselves.
Stephen23
Stephen23 2015년 7월 15일
편집: Stephen23 2015년 7월 15일
The problem is that data is not a cell array of strings, as you think it is, but actually mostly it is a cell array of cells containing strings, except for the last four cells (which are strings):
>> iscellstr(owner)
ans =
0
>> owner(1:5)
ans =
{1x1 cell}
{1x1 cell}
{1x1 cell}
{1x1 cell}
{1x1 cell}
>> owner(end-6:end)
ans =
{1x1 cell}
{1x1 cell}
{1x1 cell}
'0'
'0'
'0'
'0'
You can solve this as follows:
>> idx = cellfun('isclass',owner,'cell');
>> owner(idx) = [owner{idx}];
>> out = str2double(owner);
>> out(1:5)
ans =
1
2
3
4
5
>> out(end-6:end)
ans =
2300
2301
2302
0
0
0
0
This is the data file that I used:

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


Guillaume
Guillaume 2015년 7월 15일
str2double(vertcat(owner{:}))
works, because your each cell of your cell array (except for the last four) is actually itself a cell array which in turn contain the string.
The vertcat above convert your cell array of single cell arrays of strings into a cell array of strings.

카테고리

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