How to turn character cells into double in MATLAB?

조회 수: 2 (최근 30일)
Armando MAROZZI
Armando MAROZZI 2021년 2월 14일
편집: Stephen23 2021년 2월 14일
I have the following cell array:
load 'qq.mat'
blocks
%100×1 cell array
% {'mpta'}
% {'mpta'}
% {'mpta'}
%{'p' }
%{'s0' }
%{'s' }
%...
I am trying to turn it into double so that I can perform horzcat operations with double objects. Yet, whenever I try to use str2double I get NaNs. Nothing of what I found online works in my case. Can anyone help me with this?
Thanks!
  댓글 수: 2
Walter Roberson
Walter Roberson 2021년 2월 14일
What numeric values would you like 'mpta' and 's0' to be converted into?
Armando MAROZZI
Armando MAROZZI 2021년 2월 14일
I would like them to remain as they are, but in a format that allows me to use horzcat

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

답변 (1개)

Walter Roberson
Walter Roberson 2021년 2월 14일
blocks_numeric = double(char(blocks));
You can now horzcat() blocks_numeric and numeric data. The entries will appear as things like
109 112 116 97
112 32 32 32
115 48 32 32
The number of columns will be the same as the maximum length of character vector in blocks, which is 4 in this case.
You can later turn back into text by using
cellstr(char(TheNumericBlock(:,1:4)))
  댓글 수: 5
Walter Roberson
Walter Roberson 2021년 2월 14일
Python dataframes do not convert the text to numeric form in able to do the equivalent of horzat() them !!
MATLAB has tables, but in tables the text is not horzcat() with the numeric data.
B = {'mpta'; 'p'; 's0'}
B = 3x1 cell array
{'mpta'} {'p' } {'s0' }
v = randi(9, 3, 4)
v = 3×4
8 9 3 2 7 8 1 8 5 1 1 8
table(B, v)
ans = 3x2 table
B v ________ ________________ {'mpta'} 8 9 3 2 {'p' } 7 8 1 8 {'s0' } 5 1 1 8
Bc = categorical(B);
table(Bc, v)
ans = 3x2 table
Bc v ____ ________________ mpta 8 9 3 2 p 7 8 1 8 s0 5 1 1 8
Stephen23
Stephen23 2021년 2월 14일
편집: Stephen23 2021년 2월 14일
"You can easily do it in R or Python, creating dataframes with characters and numbers in different columns."
Not at all, you are comparing apples with oranges.
R's dataframes are more like MATLAB's tables, they are nothing like a contiguous array of numeric data.
Native Python does not have contiguous arrays of numeric data, for that you need numpy or some similar module.

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

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by