Renaming files if they meet certain array conditions

1 visualizzazione (ultimi 30 giorni)
g
g il 22 Ott 2019
Modificato: g il 22 Ott 2019
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!

Risposte (1)

Thomas Poulard
Thomas Poulard il 22 Ott 2019
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

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by