300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 修改matlab读取文件夹名字顺序

修改matlab读取文件夹名字顺序

时间:2020-11-22 16:12:28

相关推荐

修改matlab读取文件夹名字顺序

dirOutput1=dir(fullfile(str_path,’*XX’));%匹配XX;

file_path_24=sortObj(dirOutput1);

function file=sortObj(file)

for i=1:length(file)

A{i}=file(i).name;

end

% [~, ind]=natsortfiles(A);

% [~, ind]=natsortfiles(A);

[S,ind] = sort_nat(A);

for j=1:length(file)

files(j)=file(ind(j));%files1=file(ind);

end

clear file;

file=files’;

%----------------------未验证--------------------------------------------------------

function [CoS,ind,ChA,NuA] = sortnat(CoS,varargin)

% Customizable natural-order sort of a cell array of strings.

%

% © Stephen Cobeldick

%

% ### Function ###

%

% Sort the strings in a cell array of strings by character order (ASCII)

% and the value of any numeric tokens.

%

% By default sorts case-insensitive ascending, with integer numeric tokens.

% Optional inputs may be used control the format of the numeric tokens

% within the strings (see ‘Tokens’), case sensitivity and sort direction.

%

% Syntax:

% SortedCellStr = sortnat(CellStr)

% [SortedCellStr,SortIndex] = sortnat(CellStr,…);

% […] = sortnat(CellStr,RegExp)

% […] = sortnat(CellStr,RegExp,Case)

% […] = sortnat(CellStr,RegExp,Case,Descend)

% […] = sortnat(CellStr,RegExp,Case,Descend,Format)

%

% See also SORT SORTROWS UNIQUE CELLSTR REGEXP SSCANF

%

% ### RegExp Tokens ###

%

% # A numeric token consists of some combination of digits, may optionally

% include a +/- sign, decimal point, exponent, etc. The numeric tokens

% must be able to be parsed by “sscanf” (default format ‘%f’), and may

% be defined by the optional “regexp” regular expression input, eg:

%

% Regular Expression Example: | Matches Numeric Token:

% ----------------------------|---------------------------------

% ‘\d+’ | integer (default).

% ----------------------------|---------------------------------

% ‘(-|+)?\d+’ | integer with optional +/- sign.

% ----------------------------|---------------------------------

% ‘\d+(.\d+)?’ | integer or decimal.

% ----------------------------|---------------------------------

% \d+|inf | integer or infinite value.

% ----------------------------|---------------------------------

% ‘(-|+)\d+.\d+’ | decimal with +/- sign.

% ----------------------------|---------------------------------

% ‘\d+e\d+’ | exponential.

% ----------------------------|---------------------------------

% '[1-9]\d|(?<=0?)0(?!\d)’ | integer excluding leading zeros.

%

% # A character is any other single character: all other characters not

% matching the “regexp” pattern, including space & non-printing characters.

%

% ### Examples (comparison with “sort”) ###

%

% # Integer numeric tokens:

%

% A = {‘File2.txt’,‘File10.txt’,‘File1.txt’};

% sort(A)

% ans = {‘File1.txt’,‘File10.txt’,‘File2.txt’}

% sortnat(A)

% ans = {‘File1.txt’,‘File2.txt’,‘File10.txt’}

%

% # Integer or decimal numeric tokens, possibly with +/- signs:

%

% B = {‘File102.txt’,‘File11.5.txt’,‘File-1.4.txt’,‘File+0.3.txt’};

% sort(B)

% ans = {‘File+0.3.txt’,‘File-1.4.txt’,‘File102.txt’,‘File11.5.txt’}

% sortnat(B,’(-|+)?\d+(.\d+)?’)

% ans = {‘File-1.4.txt’,‘File+0.3.txt’,‘File11.5.txt’,‘File102.txt’}

%

% # Integer or decimal numeric tokens, possibly with an exponent:

%

% C = {‘A_0.56e+07’,‘A_4.3E2’,‘A_10000’,‘A_9.8’}

% sort©

% ans = {A_‘0.56e+07’,‘A_10000’,‘A_4.3E2’,‘A_9.8’}

% sortnat(C,’\d+(.\d+)?(e(+|-)?\d+)?’)

% ans = {‘A_9.8’,‘A_4.3E2’,‘A_10000’,‘A_0.56e+07’}

%

% # ASCII order (including non-printing characters):

% sortnat(CellStr,’[]’,true);

%

% ### Inputs and Outputs ###

%

% Outputs:

% Out = CellOfStrings, InC sorted into natural-order, same size as InC.

% ind = Numeric array, such that OutCoS = InCoS(ind), same size as InC.

% For debugging: each row is one string, linear-indexed from InC:

% ChA = Character array, all separate non-numeric characters.

% NuA = Numeric array, “sscanf” converted numeric values.

%

% Inputs:

% InC = CellOfStrings, whose string elements are to be sorted.

% tok = String, “regexp” numeric token extraction expression, ‘\d+’.

% cse = Logical scalar, true/false* -> case sensitive/insensitive.

% dsc = Logical scalar, true/false* -> descending/ascending sort.

% fmt = String, “sscanf” numeric token conversion format, ‘%f’.

%

% An empty input [] uses the default input option value (indicated).

%

% Outputs = [Out,ind,chr,num]

% Inputs = (InC,tok,cse,dsc*,fmt*)

DfAr = {’\d+’,false,false,’%f’}; % *{tok,cse,dsc,fmt}

DfIx = ~cellfun(‘isempty’,varargin);

DfAr(DfIx) = varargin(DfIx);

[tok,cse,dsc,fmt] = DfAr{1:4};

%

CsC = {‘ignorecase’,‘matchcase’};

SrS = [’(’,tok,’)|.’];

%

% Split strings into tokens:

[MtE,ToX] = regexp(CoS(?,SrS,‘match’,‘tokenextents’,CsC{1+cse});

%

Clx = cellfun(‘length’,MtE);

Cly = numel(MtE);

Clz = max(Clx);

%

% Initialize arrays:

ChA = char(zeros(Cly,Clz));

ChI = false(Cly,Clz);

MtC = cell(Cly,Clz);

NuA = NaN(Cly,Clz);

NuI = false(Cly,Clz);

%

% Merge tokens into cell array:

ind = 1:Cly;

for n = ind(Clx>0)

cj = cellfun(‘isempty’,ToX{n});

ChI(n,1:Clx(n)) = cj;

NuI(n,1:Clx(n)) = ~cj;

MtC(n,1:Clx(n)) = MtE{n};

end

% Transfer tokens to numeric and char arrays:

ChA(ChI) = [MtC{ChI}];

NuA(NuI) = sscanf(sprintf(’%s ‘,MtC{NuI}),fmt);

%

if cse

MtC = ChA;

else

MtC = lower(ChA);

end

%

MoC = {‘ascend’,‘descend’};

MoS = MoC{1+dsc};

%

% Sort each column of characters and numeric values:

ei = (1:Cly)’;

for n = Clz?1

% Sort char and numeric arrays:

[~,ci] = sort(MtC(ind,n),MoS);

[~,ni] = sort(NuA(ind,n),MoS);

% Relevant indices only:

cj = ChI(ind(ci),n);

nj = NuI(ind(ni),n);

ej = ~ChI(ind,n) & ~NuI(ind,n);

% Combine indices:

if dsc

ind = ind([ci(cj);ni(nj);ei(ej)]);

else

ind = ind([ei(ej);ni(nj);ci(cj)]);

end

end

%

ind = reshape(ind,size(CoS));

CoS = reshape(CoS(ind),size(CoS));

%----------------------------------------------------------------------End!

function [cs,index] = sort_nat(c,mode)

%sort_nat: Natural order sort of cell array of strings.

% usage: [S,INDEX] = sort_nat©

%

% 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

% Author: Douglas M. Schwarz

% Email: dmschwarz=ieeeorg, dmschwarz=urgradrochesteredu

% 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©;

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);

end

index = reshape(index,size©);

cs = c(index);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。