我在阅读矩阵时遇到了问题。 源矩阵是:
# Source : sampledSurface sampledSurface
# Faces : 308
# Time sum(magSf) areaAverage(k) areaAverage(U)
1.831000e+04 6.665915e-02 2.019808e-03 (4.761775e-01 -1.966368e-23 -9.890843e-10)
我的问题是导入括号内的数据。矢量应该有6列:
A =
1.831000e+04 6.665915e-02 2.019808e-03 4.761775e-01 -1.966368e-23 -9.890843e-10
我已经做了几次尝试让这个工作,我尝试在互联网上进行一些研究后编写代码,但我仍然有不好的结果。 我知道我的代码不对。这是我试图使用的代码:
filename = 'directory\filename.dat '
delimiter = '\t';
formatSpec = '%s%s%s%s%[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter);
fclose(fileID);
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
raw(1:length(dataArray{col}),col) = dataArray{col};
end
答案 0 :(得分:1)
所以问题是从文件中读取后从行中删除括号?您可以在字符串中搜索特定的子字符串或模式,然后将其删除。
我们可以从您的dataArray
变量中执行此操作,因此在fclose(fileID);
之后放置以下代码行:
theArrayString = dataArray{4,1}; % this will get the array string from dataArray
theArrayString(regexp(theArrayString,'[(,)]'))=[]; % this uses a regular expression to search for brackets in the string, and where ever it finds a bracket it deletes it (= [])
results = str2num(theArrayString); % this will convert the string into an array of numbers
正则表达式是一种快速的方法,但一开始很难玩。因此,如果您将来需要类似的东西,您还可以使用strfind('(')
和strfind(')')
为您提供括号所在的索引,然后从字符串中删除它们,例如
theArrayString([strfind(theArrayString,'(') strfind(theArrayString,')')]) = []
甚至使用strrep
将给定的子字符串替换为另一个子字符串(以删除它将为空),例如。
theArrayString = strrep(theArrayString,'(','');
theArrayString = strrep(theArrayString,')','');