查看单个帖子
旧 2019-12-10, 20:30   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 跳过在MATLAB中阅读字符串

MATLAB中是否有一条简单的命令可以防止程序在读取字符时崩溃?

我使用xlsread读取( xlsread )矩阵数据,因为它们具有标题,所以第一行和第一列被忽略,因此:

data = xlsread ('C:\file.xls') 会导致data大小为(19399)。

我有一个问题,有些单元格缺少数据,并且写为“ missing”,在某些数据集上,我的标题重新出现在中间。

有没有一种方法可以跳过这些字符而不会导致程序崩溃,而我不得不在excel中打开文件并删除这些字段?

谢谢

抱歉,更新晚了。这是我正在使用的代码:

[a,patha]=uigetfile({'*.csv'},'Select the file' ,'c:\Data\2010'); file1=[patha a]; %# get a file ID fid = fopen(file1,'rt'); newf= textscan(fid, ['%s' repmat('%f',1,27)], 'HeaderLines', 1, 'Delimiter', ','); fclose(fid) ; %//Make time a datenum of the first column time = datenum(newf{1} ); %//Find the difference in minutes from each row timeDiff = round(diff(datenum(time)*(24*60))); %//the rest of the data newf = cell2mat(newf(2:28)); 我得到的错误是:

??? Error using ==> cat CAT arguments dimensions are not consistent. Error in ==> cell2mat at 81 m{n} = cat(2,c{n,:}); Error in ==> testprogram at 31 pwr = cell2mat(newf(2:28)); 这是由于我选择的文件中的字符。当我手动删除它们时,它消失了



回答:

如果字符串不符合预期,则Textscan失败。空条目在连接时会导致问题-您的数组的列数将不均匀。

textscan('bla,5.4,missing,3,3,3.4','%s%f%f%f%f%f','Delimiter',',') ans = {1x1 cell} [5.4000] [0x1 double] [0x1 double] [0x1 double] [0x1 double] 但是,您可以使用'TreatAsEmpty'将'missing'视为空(即将它们替换为NaN)

textscan('bla,5.4,missing,3,3,3.4','%s%f%f%f%f%f','Delimiter',',','TreatAsEmpty','missing') ans = {1x1 cell} [5.4000] [NaN] [3] [3] [3.4000] 这使您可以毫无问题地运行cell2mat。



更多&回答...
poster 当前离线   回复时引用此帖