Matlab 使用正则表达式从目录加载文件

问题描述

我为此找了很多,但没有找到任何东西。我对 matlab 和正则表达式很陌生。

我的问题是,有一个目录路径“dir”,其中只有一个 .txt 文件。但是我不知道txt文件文件名。我想加载这个文件

我尝试了多种方法,但找不到解决方案。

foo = load(fullfile(dir,'-regexp','*.txt'))

感谢您的帮助!

解决方法

该语法对 fullfile 无效,而 dir 是一个内置函数,您似乎将其用作变量...这里有一些更清晰的内容,应该可以使用当给定的 txt

中只有一个 folder 文件时
folder = 'my\folder\path\';
files = dir( fullfile( folder,'*.txt' ) );

if numel( files ) ~= 1
    error( 'More or less than one .txt file found!' );
end

filepath = fullfile( files(1).folder,files(1).name );

foo = load( filepath ); % load is designed for .mat files,if your .txt contains anything
% non-numeric then you may want something more like readtable here...