matlab对文件目录进行自然排序
作者:tongqingliu
转载请注明出处:http://www.cnblogs.com/liutongqing/p/7072878.html
觉得有帮助?欢迎来打赏

# matlab对文件目录进行自然排序
[原博客阅读效果更佳。](http://www.cnblogs.com/liutongqing/p/7072878.html)
比如我新建一个tmp文件夹,在该文件夹下新建以下txt文件进行测试
```
a1.txt
a2.txt
a3.txt
a11.txt
a12.txt
b10.txt
```
返回到tmp的上一层文件夹,编写代码,查看该文件夹下的所有文件。
```matlab
clear;clc;close all
d = dir('tmp');
for i = 3:length(d)
disp(d(i).name)
end
```
MATLAB返回的结果是
```
a1.txt
a11.txt
a12.txt
a2.txt
a3.txt
b10.txt
```
WTF,什么鬼,有些时候我们不希望得到这样的结果,吓得我赶紧百度了一下
http://blog.csdn.net/g0m3e/article/details/52982737
看到这个人的博客,实现了我想要的结果,但是链接挂掉了。
换个地,找到了解决办法。
新建函数sort_nat.m
function [cs,index] = sort_nat(c,mode)
%sort_nat: Natural order sort of cell array of strings.
% usage: [S,INDEX] = sort_nat(C)
%
% where,
% C is a cell array (vector) of strings to be sorted.
% S is C, sorted in natural order.
% INDEX is the sort order such that S = C(INDEX);
%
% Natural order sorting sorts strings containing digits in a way such that
% the numerical value of the digits is taken into account. It is
% especially useful for sorting file names containing index numbers with
% different numbers of digits. Often, people will use leading zeros to get
% the right sort order, but with this function you don't have to do that.
% For example, if C = {'file1.txt','file2.txt','file10.txt'}, a normal sort
% will give you
%
% {'file1.txt' 'file10.txt' 'file2.txt'}
%
% whereas, sort_nat will give you
%
% {'file1.txt' 'file2.txt' 'file10.txt'}
%
% See also: sort
% Version: 1.4, 22 January 2011
% Author: Douglas M. Schwarz
% Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
% Real_email = regexprep(Email,{'=','*'},{'@','.'})
% Set default value for mode if necessary.
if nargin < 2
mode = 'ascend';
end
% Make sure mode is either 'ascend' or 'descend'.
modes = strcmpi(mode,{'ascend','descend'});
is_descend = modes(2);
if ~any(modes)
error('sort_nat:sortDirection',...
'sorting direction must be ''ascend'' or ''descend''.')
end
% Replace runs of digits with '0'.
c2 = regexprep(c,'\d+','0');
% Compute char version of c2 and locations of zeros.
s1 = char(c2);
z = s1 == '0';
% Extract the runs of digits and their start and end indices.
[digruns,first,last] = regexp(c,'\d+','match','start','end');
% Create matrix of numerical values of runs of digits and a matrix of the
% number of digits in each run.
num_str = length(c);
max_len = size(s1,2);
num_val = NaN(num_str,max_len);
num_dig = NaN(num_str,max_len);
for i = 1:num_str
num_val(i,z(i,:)) = sscanf(sprintf('%s ',digruns{i}{:}),'%f');
num_dig(i,z(i,:)) = last{i} - first{i} + 1;
end
% Find columns that have at least one non-NaN. Make sure activecols is a
% 1-by-n vector even if n = 0.
activecols = reshape(find(~all(isnan(num_val))),1,[]);
n = length(activecols);
% Compute which columns in the composite matrix get the numbers.
numcols = activecols + (1:2:2*n);
% Compute which columns in the composite matrix get the number of digits.
ndigcols = numcols + 1;
% Compute which columns in the composite matrix get chars.
charcols = true(1,max_len + 2*n);
charcols(numcols) = false;
charcols(ndigcols) = false;
% Create and fill composite matrix, comp.
comp = zeros(num_str,max_len + 2*n);
comp(:,charcols) = double(s1);
comp(:,numcols) = num_val(:,activecols);
comp(:,ndigcols) = num_dig(:,activecols);
% Sort rows of composite matrix and use index to sort c in ascending or
% descending order, depending on mode.
[unused,index] = sortrows(comp);
if is_descend
index = index(end:-1:1);
end
index = reshape(index,size(c));
cs = c(index);
调用这个函数,在之前的代码中添加几行
clear;clc;close all
d = dir('tmp');
nameCell = cell(length(d)-2,1);
for i = 3:length(d)
disp(d(i).name)
nameCell{i-2} = d(i).name;
end
d2 = sort_nat(nameCell)
下面是见证奇迹的时刻
d2 =
'a1.txt'
'a2.txt'
'a3.txt'
'a11.txt'
'a12.txt'
'b10.txt'
这样就方便处理文件了。
参考:
http://cn.mathworks.com/matlabcentral/fileexchange/34464-customizable-natural-order-sort
matlab对文件目录进行自然排序的更多相关文章
- Java基础知识强化之集合框架笔记46:Set集合之TreeSet存储自定义对象并遍历练习2(自然排序:Comparable)
1. TreeSet存储自定义对象并遍历练习2: (1)Student.java package cn.itcast_06; /* * 如果一个类的元素要想能够进行自然排序,就必须实现自然排序接口 * ...
- Java基础知识强化之集合框架笔记45:Set集合之TreeSet存储自定义对象并遍历练习1(自然排序:Comparable)
1. 自然排序: TreeSet会调用集合元素的compareTo(Object obj)方法来比较元素之间的大小关系,然后将集合元素按照升序排列,这种方式就是自然排序. Java中提供了一个Comp ...
- Java基础知识强化之集合框架笔记44:Set集合之TreeSet保证元素唯一性和自然排序的原理和图解
1. TreeSet保证元素唯一性和自然排序的原理和图解 2. TreeSet唯一性以及有序性底层剖析: 通过观察TreeSet的add()方法,我们知道最终要看TreeMap的put()方法. 跟踪 ...
- Collections之sort的两个方法(自然排序和自定义比较器排序)
Collections是个服务于Collection的工具类(静态的),它里面定义了一些集合可以用到的方法. 本文演示了Collections类里sort()的两个方法.第一种只需传入被排序的集合,便 ...
- 浅析pinyin4j源码 简单利用pinyin4j对中文字符进行自然排序(转)
pinyin4j项目 官网地址 http://pinyin4j.sourceforge.net/ 我们先把资源下载下来,连同源码和jar包一起放入工程.如下图: 接下来在demo包下,我们写一个测试 ...
- TreeSet集合排序方式一:自然排序Comparable
TreeSet集合默认会进行排序.因此必须有排序,如果没有就会报类型转换异常. 自然排序 Person class->实现Comparable,实现compareTo()方法 package H ...
- 《java入门第一季》之集合框架TreeSet存储元素自然排序以及图解
这一篇对TreeSet做介绍,先看一个简单的例子: * TreeSet:能够对元素按照某种规则进行排序. * 排序有两种方式 * A:自然排序: 从小到大排序 * B:比较器排序 Comp ...
- TreeSet集合的自然排序与比较器排序、Comparable接口的compareTo()方法
[自然排序] package com.hxl; public class Student implements Comparable<Student> { private String n ...
- TreeSet的自然排序(自定义对象 compareTo方法)
>要实现自然排序,对象集合必须实现Comparable接口,并重写compareTo()方法 >一般需求中描述的是"主要条件",如:按姓名长度排序. 需注意次要条件 ...
随机推荐
- IOS打包相关问题
使用了AFNetworking框架,模拟器和真机运行都不报错,但是提交商店报错Unsupported Architecture. Your executable contains unsupporte ...
- InputStream类详解
InputStream这个抽象类是所有基于字节的输入流的超类,抽象了Java的字节输入模型.在这个类中定义了一些基本的方法.看一下类的定义: public abstract class InputSt ...
- Python数据类型和变量
一.数据类型1.整型整型类型比较简单,就是我们数学中的正整数(1,2,520..).负整数(-2,-9..);与java不同的是,python中的整数可以无限大,而java的整数类型int为四个字节, ...
- React入门---开始前的准备(上)-2
开始前准备: 1.安装配置nodeJs(nodeJS官网) 检查安装成功: node -v npm -v 2.使用NPM配置React开发环境 (1). 创建项目文件夹(创建文件夹时,文件夹名不要起为 ...
- js导出CSV
<html> <head> <meta http-equiv="content-type" content="text/html; char ...
- Python beautifulsoup 中文乱码
在爬百度"今日热点事件排行榜"的时候发现打印在控制台的中文全部显示乱码,开始怀疑控制台的原因导致了乱码,后来输出一个中文,发现显示正常. #-*- coding:utf-8 -*- ...
- 解决shiro和quartz2 版本冲突问题
修改build.gradle compile ("org.quartz-scheduler:quartz:2.2.3") compile ("org.apache.s ...
- PHP基础入门(二)---入门必备哦!
前言 在上一章中,我们初步了解了PHP的网页基础和PHP的入门基础,今天继续给大家分享更多有关PHP的知识. 理论知识看起来可能比较枯燥一些,但是我们的实践(敲代码)毕竟离不开它. 只有理论与实践相结 ...
- RabbitMQ系列教程之二:工作队列(Work Queues)
今天开始RabbitMQ教程的第二讲,废话不多说,直接进入话题. (使用.NET 客户端 进行事例演示) 在第一个教程中,我们编写了一个从命名队列中发送和接收消息的程序. ...
- 增强 Sublimetext3
1.让你的粘贴保留原有缩进 Preferences -> Key Binding 中新增: [ , { "keys": ["ctrl+v"], " ...