【问题标题】:Rearrange all strings in vector Matlab重新排列向量Matlab中的所有字符串
【发布时间】:2017-03-10 18:14:24
【问题描述】:

我有一个大单元向量,其中包含使用

的目录中的文件名

listing = dir(['foldername','\*.xlsx'])

文件名称中有日期,但格式难以确定顺序。例如,每个文件都称为 dataDDMMYYY.xlsx,其中 DDMMYYY 是表示数据日期的数字。

我想获得一个位置向量,将文件从最新到最旧排序。一个建议是使用arrayfun 从字符串中删除“data”和“xlsx”,并使用new=[old(9:12), old(7:6), old(5:6)] 之类的东西重新排列为YYYYMMDD。 但是,我还没有找到这些没有错误的组合。 有没有一种优雅的方法来实现这一点?

【问题讨论】:

  • 看看regexp,我确信有一个正则表达式可以用来提取这种特定的日期格式。你甚至可以在网上找到一个。

标签: arrays string matlab vector ranking


【解决方案1】:

您可以使用函数datenum,根据指定的格式(在您的情况下为ddmmyyyy)为每个日期输出一个数字(较小=较旧,较大=较新)。然后您可以使用这些数字对日期进行排序。此方法假定所有文件都是.xls.xlsx,并且它们的名称在实际日期之前以data 开头:

listing = dir(['fildername','\*.xls*']); % list all xls and xlsx files in directory
names = {listing.name}; % cell array with names only

[~,dates,~] = cellfun(@fileparts, names, 'uni', 0); % apply fileparts to every cell
dates = cell2mat(dates'); % convert to char matrix (all the string have to be equally long)
dates = dates(:,5:end); % remove 'data' from each string

new_dates = datenum(dates, 'ddmmyyyy'); % extract date number
[sorted_new_dates, index] = sort(new_dates, 'descend'); % sort from newest to oldest

然后您可以使用index 从最新到最旧处理您的原始文件。

listing(index).name % print sorted filenames :)

【讨论】:

  • 谢谢。有些文件夹确实混合了 xlsx 和 xls。如何在没有循环的情况下调用文件部分?
  • 我们确定每个文件都以data 开头吗?
  • 是的。只有扩展名不同
  • 我编辑了答案,这适用于 xls 和 xlsx。您可以使用cellfun 在元胞数组的每个元胞上使用文件部分。希望这就是你要找的! :)
  • 优秀。谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 2018-03-07
  • 1970-01-01
  • 2015-09-09
  • 2011-11-22
相关资源
最近更新 更多