So, I have two folders at different locations and I loop through the files of one of these folders (A). I want to get the filename and foldername of the file in the other folder (B) which has the same name as the file I am currently looking at in my loop. I do this because I want the full filepath of the file with the same name in another folder with subfolders.
Here some code for explanation:
a_paths = dir("D:\folder1");
b_paths = dir("D:\folder2\**\*"); % this one has files in subfolders
for i = 1 :length(a_paths)
[path,current_name,ext] = fileparts(a_paths(i).name);
% does not work:
matched_name = b_paths.name(b_paths.name == current_name);
matched_folder = b_paths.folder(b_paths.name == current_name);
end
But this does not work. I usually use R and obviously don't know how to work with these not-very-handy structure arrays in Matlab. How can I do this without needing to loop through all files in the other folder as well? Surely, there must be a better way?
Edit This here does what I want, but it's way to complicated to be the easiest way:
for i = 1 :length(a_paths)
[path,current_name,ext] = fileparts(a_paths(i).name);
for j = 1 :length(b_paths)
[path,other_name,ext] = fileparts(a_paths(i).name);
if current_name == other_name
path = fullfile(b_paths(j).folder, current_name);
end
end
end
CodePudding user response:
You can use ismember()
to check which elements of an array can be found in another array (or structure):
% List elements of both folder (and eventually subfolder with \**\)
A = dir('Path\to\A');
B = dir('Path\to\B');
% Get the filename or foldername in B that can be found in A
x = B(ismember({B.name},{A.name}));
% Eliminate the folders and construct the fullpath
duplicateB = fullfile({x(~[x.isdir]).folder},{x(~[x.isdir]).name})
You just need to get used to the matlab synthax:
()
-> for indexing or function call[]
-> for array{}
-> for structure array or cell array