从cell转化到double
经常困惑于在读入文件中既有字符串,又包含数字情况下而不能用‘%f’格式。于是乎,调用‘%s’格式的结果是读入的dataArray为字符串cell。此时如果需要转化dataArray中的数字字符串为double类型,通常可以有以下几种方法:
1. for循环
2. cellfun(@(x), str2num(dataArray))
3. str2num(char(dataArray))
接下来分别以上述三种方法为例进行对比。在此先给出结论,目前来说第3种方法str2num(char(dataArrary))最有效。
下边是一个简单的matlab程序,分别记录三种方法的CPU时间。在读入dataArray为500*4的情况下,耗时分别为
进一步, 增加读入数据量,提升dataArray至5000*4和50000*4的情况下,耗时时间如下
可见,在数据量较小的情况下,第3种方法最有效,可是当数据量比较大的时候,三种方法相当,而且猜测第1,3种方法同理。
附:源程序
clear all,clc
%% creat a data file
data_creat = log(rand(500,4)*100);
fileID = fopen('data_creat.txt','w');
fprintf(fileID,'%6s %6s %6s %6s\n','data1','data1','data1','data1');
fprintf(fileID,'%.6f %.6f %.6f %.6f \n',data_creat);
fclose(fileID);
%% read the data from the ceated file into a cell
fileID = fopen('data_creat.txt');
formatSpec = '%s %s %s %s \n';
dataArray = textscan(fileID, formatSpec, 'HeaderLines',1);
fclose(fileID);
% first method: for loop
tic
dataCol = [dataArray{:,1}, dataArray{:,2}, dataArray{:,3}, dataArray{:,4}];
for i = 1:size(dataCol,1)
data(i,1) = str2num(dataCol{i,1});
data(i,2) = str2num(dataCol{i,2});
data(i,3) = str2num(dataCol{i,3});
data(i,4) = str2num(dataCol{i,4});
end
toc
% second method: cellfun
clearvars data
tic
data(:,1) = cellfun(@(x) str2num(x), dataArray{1,1});
data(:,2) = cellfun(@(x) str2num(x), dataArray{1,2});
data(:,3) = cellfun(@(x) str2num(x), dataArray{1,3});
data(:,4) = cellfun(@(x) str2num(x), dataArray{1,4});
toc
% third method: str2num(char)
clearvars data
tic
data(:,1) = str2num(char(dataArray{:,1}));
data(:,2) = str2num(char(dataArray{:,2}));
data(:,3) = str2num(char(dataArray{:,3}));
data(:,4) = str2num(char(dataArray{:,4}));
toc
网友评论