insert file from different folder based on the file name

3 vues (au cours des 30 derniers jours)
farhah muhammad
farhah muhammad le 28 Avr 2023
I have two folders (for example folder A and folder B) each contains 26 files.
folder A
1.A003419.mat
2.
.
26.
folder B
1.FT03419.mat
2.
.
26.
As you can see, they have 9 similar alphabet at the back of each file name (bold as below),
A003419.mat is a corresponding to FT03419.mat
however, those two folders have different variables, and I need to insert the one variable from FT03419 to A003419..
loop shouLd be great, but I do not know how to insert variable in many files
thank you SMART PEOPLE!

Réponses (1)

Pro
Pro le 28 Avr 2023
Modifié(e) : Pro le 28 Avr 2023
Assuming that the variable you want to insert from FT03419.mat to A003419.mat has the same name in both files, you can use the following Matlab code to loop through the files in folder A and B, match the files based on their names, and insert the variable from the corresponding file in folder B to the corresponding file in folder A:
folderA = 'path/to/folder/A/';
folderB = 'path/to/folder/B/';
variableName = 'name_of_variable_to_insert';
filesA = dir(fullfile(folderA, '*.mat'));
filesB = dir(fullfile(folderB, '*.mat'));
for i = 1:length(filesA)
filenameA = filesA(i).name;
filenameB = strrep(filenameA, 'A', 'FT');
filePathA = fullfile(folderA, filenameA);
filePathB = fullfile(folderB, filenameB);
% load the variable from the file in folder B
variable = load(filePathB, variableName);
variable = variable.(variableName);
% insert the variable into the file in folder A
save(filePathA, variableName, '-append');
end
This code uses the `dir` function to get a list of all the .mat files in each folder, and then loops through the files in folder A. For each file in folder A, it constructs the corresponding filename in folder B by replacing the 'A' with 'FT'. It then constructs the full file paths for both files using the `fullfile` function. Next, it loads the variable from the file in folder B using the `load` function and the name of the variable you want to insert. Finally, it inserts the variable into the file in folder A using the `save` function with the `-append` flag to add the variable to the existing .mat file.
Note that if the variable you want to insert has a different name in each file, you will need to modify this code to handle that case.
  2 commentaires
farhah muhammad
farhah muhammad le 28 Avr 2023
Wow, I would like try !
thank you!!!
farhah muhammad
farhah muhammad le 9 Mai 2023
turn out, my variable nme is not similar, the variable in folder b has two column. still trying to get this

Connectez-vous pour commenter.

Catégories

En savoir plus sur File Operations dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by