Converting all texts to numbers in a cell that has numbers and texts
3 次查看(过去 30 天)
显示 更早的评论
Hello there, I have a structure (X) that contains text and numbers and I would like to convert them to a vector with numbers only. So, I just wanted any text to be written as zero instead of a text as '0'. I'm using the code below. Anyone can help please.
% my cell is F with size 58X11 Cell
% It looks as below (e.g.)
% F = ['0' 1 '0' 3'
% 4 '0' 34 10]
% I would like to make looks like the below
% F = [0 1 0 3
% 4 0 34 10]
% my code
for i = 1:L
E = C{1,i} % the structure contains text and numbers. The texts are written as '0', which I wnat to conver to number 0
F = E(9:66,2:12);
X = str2double(F); % here X is double but the '0' became 0, while the numbers became Nan
end
0 个评论
回答(1 个)
Walter Roberson
2021-2-14
X = zeros(size(F));
mask = cellfun(@ischar, F);
X(~mask) = cell2mat(F(~mask)); %copy non-text directly
X(mask) = str2double(F(mask)); %convert the text
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!