MATLAB自动生成的函数可输入变量而不是.txt文件 [英] MATLAB automatically generated function to input a variable instead of a .txt file
问题描述
MATALB的导入数据"功能自动生成一个输入.txt文件并输出表的函数.此函数的前几行如下所示:
MATALB's "Import Data" feature automatically generates a function which inputs a .txt-file and outputs a table. The first few lines of this function looks like this:
function output= myfunction(filename)
delimiter = {';','='};
%% Read columns of data as text:
formatSpec = '%s%s%s%s%s%s%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string', 'ReturnOnError', false);
%% Close the text file.
fclose(fileID);
但是,我需要此函数来输入变量,而不是将具有完全相同效果的.txt文件.我已经将所有数据以变量的形式存储在.txt文件中.我以为我可以用变量替换filename
,并删除fileID
和fclose
行的代码,但这是行不通的.
However, I need this function to input a variable instead of a .txt-file that will have the exact same effect. I have all the data stored in the .txt-file in the form of a variable already. I thought I could simply replace filename
with the variable, and delete of the fileID
and fclose
lines of code, but it doesn't work.
推荐答案
在循环中使用此自动生成的函数循环遍历您拥有的文件(名称)
Use this auto-generated function in a loop to loop through the file(name)s that you have
% path to folder with txt-files
pFlr = pwd; % path to working directory
Lst = dir( fullfile(pFldr,'*.txt') ); % only get txt-files
for i = 1:length(Lst)
% path to file
pFl = fullfile( Lst(i).folder,Lst(i).name );
% read file by calling the auto-generated function
Dat1 = myfunction( pFl );
end
通过这种方式,您可以循环访问所有文件,例如将数据存储在表中:
In this way, you can access all your files in a loop and, e.g. store the data in a table:
k = 1; % control variable
for i = 1:length(Lst)
% path to file
pFl = fullfile( Lst(i).folder,Lst(i).name );
% read file by calling the auto-generated function
Dat1 = myfunction( pFl );
% do something with this data, e.g. store it
if i == 1 % allocate data if
Dat = Dat1;
% extend for allocation
vSz= height(Dat1)*length(Lst);
Dat(vSz,:) = Dat1(1,:); % assign the first row of the first table to the last row of the allocated table to expand it
else
Dat(k:k+size(Dat1)-1,:) = Dat1;
end
k = k + size(Dat1);
end
% crop table
Dat = Dat(1:k-1,:);
这篇关于MATLAB自动生成的函数可输入变量而不是.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!