How to turn character cells into double in MATLAB?
Show older comments
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 Comments
Walter Roberson
on 14 Feb 2021
What numeric values would you like 'mpta' and 's0' to be converted into?
Armando MAROZZI
on 14 Feb 2021
Answers (1)
Walter Roberson
on 14 Feb 2021
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 Comments
Armando MAROZZI
on 14 Feb 2021
What you believe you need cannot be done in MATLAB. Numeric arrays can never have printable characters in them in MATLAB. Or any other programming language that I can think of.
You can use cell() arrays. You can use table() . You can even convert to categorical() and use that in tables to get rid of the apostrophes.
You can convert the double to character.
B = {'mpta'; 'p'; 's0'}
v = randi(9, 3, 4)
[B, string(v)]
[B, compose("%0.3f", v)] %to control the exact format of converting the numbers
Armando MAROZZI
on 14 Feb 2021
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'}
v = randi(9, 3, 4)
table(B, v)
Bc = categorical(B);
table(Bc, v)
"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.
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!