0%

MATLAB按数字顺序读取文件

最近手上一个项目需要生成一个超大文件,但是内存不够需要在超算分散运行,生成了大量的散碎文件最终需要拼凑,以下代码可以将文件按自然数顺序排序,并且将矩阵在第三维度进行拼凑

MATLAB按数字顺序读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
clc
clear all

dbstop if error

trainPath='E:\project\16面阵\file7\';
train = dir([trainPath '*.mat']);
train_num = length(train);
data_all=[];

sort_nat_name=sort_mat({train.name});

for i=1:train_num
data = load(sort_nat_name{i});
data_matx = cell2mat(struct2cell(data));
if i == 1
data_all(:,:,size(data_all,3):size(data_matx,3)) = data_matx;
else
data_all(:,:,size(data_all,3) + 1:size(data_all,3)+size(data_matx,3)) = data_matx;
end
end



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

if nargin < 2
mode = 'ascend';
end

modes = strcmpi(mode,{'ascend','descend'});
is_descend = modes(2);
if ~any(modes)
error('sort_nat:sortDirection',...
'sorting direction must be ''ascend'' or ''descend''.')
end

c2 = regexprep(c,'\d+','0');

s1 = char(c2);
z = s1 == '0';

[digruns,first,last] = regexp(c,'\d+','match','start','end');

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

activecols = reshape(find(~all(isnan(num_val))),1,[]);
n = length(activecols);

numcols = activecols + (1:2:2*n);

ndigcols = numcols + 1;

charcols = true(1,max_len + 2*n);
charcols(numcols) = false;
charcols(ndigcols) = false;

comp = zeros(num_str,max_len + 2*n);
comp(:,charcols) = double(s1);
comp(:,numcols) = num_val(:,activecols);
comp(:,ndigcols) = num_dig(:,activecols);

[unused,index] = sortrows(comp);
if is_descend
index = index(end:-1:1);
end
index = reshape(index,size(c));
cs = c(index);
end
------ 本文结束感谢您的阅读 ------