我正在尝试在Matlab中创建一个脚本,从文件中提取数据并生成数据数组。由于数据是一个字符串,我试图将其拆分为列,然后进行转置,并再次将其拆分为列以填充数组。
当我运行脚本时,我没有收到任何错误,但我也没有得到任何有用的数据。我告诉它显示最终的矢量(Full_Array
),我得到{1×4 cell} 8次。当我尝试使用strsplit
时,我收到错误:
'使用strsplit时出错(第80行)第一个输入必须是字符向量或字符串标量。'
我是Matlab的新手,老实说,在阅读了类似的线程和文档之后,我不知道如何修复它。我已经附上了下面的代码和数据。谢谢。
clear
File_Name = uigetfile; %Brings up windows file browser to locate .xyz file
Open_File = fopen(File_Name); %Opens the file given by File_Name
File2Vector = fscanf(Open_File,'%s'); %Prints the contents of the file to a 1xN vector
Vector2ColumnArray = strsplit(File2Vector,';'); %Splits the string vector from
%File2Vector into columns, forming an array
Transpose = transpose(Vector2ColumnArray); %Takes the transpose of Vector2ColumnArray
%making a column array into a row array
FullArray = regexp(Transpose, ',', 'split');
我试图读取的数据来自一个名为methylformate.xyz的.xyz文件,这里是数据:
O2,-0.23799,0.65588,-0.69492;
O1,0.50665,0.83915,1.47685;
C2,-0.32101,2.08033,-0.75096;
C1,0.19676,0.17984,0.49796;
H4,0.66596,2.52843,-0.59862;
H3,-0.67826,2.36025,-1.74587;
H2,-1.03479,2.45249,-0.00927;
H1,0.23043,-0.91981,0.45346;
答案 0 :(得分:0)
当我开始使用Matlab时,我也遇到了数据结构问题。最后一行
FullArray = regexp(Transpose, ',', 'split');
拆分每一行并将其存储在单元格数组中。为了访问单个字符串,您必须使用大括号将其编入FullArray:
FullArray{1}{1} % -> 'O2'
FullArray{1}{2} % -> '-0.23799'
FullArray{2}{1} % -> 'O1'
FullArray{2}{2} % -> '0.50665'
因此,第一个数字对应于行,第二个数字对应于行中的特定元素。
但是,Matlab中的functions更容易根据正则表达式加载文本文件。
答案 1 :(得分:0)
通常,读取混合数据的最简单函数是readtable
。
data = readtable('methylformate.txt');
然而,在你的情况下,这更复杂,因为
readtable
无法处理.xyz文件,因此您必须复制到.txt 您可以遍历每一行并使用textscan
,如下所示:
fid = fopen('methylformate.xyz');
tline = fgetl(fid);
myoutput = cell(0,4);
while ischar(tline)
myoutput(end+1,:) = textscan(tline, '%s %f %f %f %*[^\n]', 'delim', ',');
tline = fgetl(fid);
end
fclose(fid);
输出是字符串或双精度的单元格数组(视情况而定)。