필터 지우기
필터 지우기

insert file from different folder based on the file name

조회 수: 7 (최근 30일)
farhah muhammad
farhah muhammad 2023년 4월 28일
댓글: farhah muhammad 2023년 5월 9일
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!

답변 (1개)

Pro
Pro 2023년 4월 28일
편집: Pro 2023년 4월 28일
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
farhah muhammad
farhah muhammad 2023년 4월 28일
Wow, I would like try !
thank you!!!
farhah muhammad
farhah muhammad 2023년 5월 9일
turn out, my variable nme is not similar, the variable in folder b has two column. still trying to get this

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by