필터 지우기
필터 지우기

Renaming files if they meet certain array conditions

조회 수: 1 (최근 30일)
g
g 2019년 10월 22일
편집: g 2019년 10월 22일
I have some arbitrary files in a directory "my_directory":
file_1002.txt
file_1012.txt
file_1023.txt
file_2045.txt
each with some value.
In Matlab, I have a corresponding array of values, call it "my_array"
1002
1012
1023
2045
Now, I want to check whether these values are within 10 of values in another array "array_2"
1000
1010
2055
For example, file_1002.txt has a value of 1002, which is within 10 of values in array_2 (namely 1000 and 1010). Therefore, file_1002.txt will be renamed file_1002_new.txt. Likewise, for 1012 and 2045. However, file_1023.txt has a value of 1023, which is not within 10 of any values in array_2, so file_1023.txt does not need to be renamed.
How could this scheme be accomplished? Thanks!

답변 (1개)

Thomas Poulard
Thomas Poulard 2019년 10월 22일
Here is a piece of code that should be working. I am not familiar with renaming directly the files in the specific folder, so this code makes you load the txt file if it has to be renamed before saving it with its new name. Hope this helps :)
Thomas
clear
clc
txtFiles = dir(fullfile([path '/*.txt'])) ; % List of your txt files
% That was just for me but this is your matrix "my_array"
my_array = zeros(length(txtFiles)) ;
for ii = 1 : length(txtFiles)
my_array(ii) = str2double(txtFiles(ii).name(6:9)) ;
end
array_2 = [1000;1010;2055] ;
% for every file, and for every number in array_2, check if it is in between the range of 10 values you want
for ii = 1 : length(my_array)
for jj = 1 : length(array_2)
my_range = array_2(jj)-10 : array_2(jj)+10 ; % Specify the range
if my_array(ii) >= my_range(1) && my_array(ii) <= my_range(end)
data = dlmread([txtFiles(ii).name(1:9) '.txt']) ;
dlmwrite([path '/' txtFiles(ii).name(1:9) '_new.txt'], data)
end
end
end

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by