Movefile when string is a variable - matlab

This is within a forloop aimed at moving multiple files within multiple folders into the 'RawData' directory. I am having issues with using movefile. I would like the file being moved to be a varaible and not a string typed into the command.
Here is a portion of the folder list if needed to better understand:
'Data-20141003T091843-1-Eyes Open on Flat Surface-Force.csv'
'Data-20141003T091843-1-Eyes Open on Flat Surface-Results.csv'
'Data-20141003T091923-2-Eyes Closed on Flat Surface-Force.csv'
'Data-20141003T091923-2-Eyes Closed on Flat Surface-Info.csv'
'Data-20141003T091923-2-Eyes Closed on Flat Surface-Results.csv'
'Data-20141003T092208-3-Limits of Stability-Force.csv'
'Data-20141003T092208-3-Limits of Stability-Info.csv'
>>foldername = foldername.name;
directoryname = 'C:\Users\murphy\Documents\MATLAB\RawData\';
folderdirectory = strcat(directoryname,foldername);
cd(folderdirectory);
folderdir = dir('*.csv');
folderList = {folderdir.name}'; %List of Files in folder
for f = 1:length(folderList) **movefile(folderList(f),'C:\Users\murphy\Documents\MATLAB\RawData')**
end

folderList is a cellstr.
In your for loop you need to pass folderList{f} instead of folderList(f).
for f = 1:length(folderList)
movefile(folderList{f},'C:\Users\murphy\Documents\MATLAB\RawData')
end

Related

Matlab - Reading names of files in a directory [duplicate]

This question already has answers here:
How to put these images together?
(1 answer)
MATLAB - iterate function on all files in a directory
(1 answer)
Closed last year.
For files with some repeating numerical pattern like file0001, file0002...file0100, I've written the following script to operate on the input files and save the results with the same name.
% The folder has 100 files to be operated on
% "save_filename" is the name of data saved for the "inname" file
for k = 1:100
inputfiledir = './Data/Category1/';
if (k<10)
save_filename = sprintf('score_sp1_a000%d',k);
inname = sprintf('sp1_a000%d',k);
elseif (k>=10)
save_filename = sprintf('score_sp1_a00%d',k);
inname = sprintf('sp1_a00%d',k);
end
if (k>=100)
save_filename = sprintf('score_sp1_a0%d',k);
inname = sprintf('sp1_a0%d',k);
end
[prediction,score] = predict_class(trainedNet,strcat(inputfiledir,inname,'.wav'));
save(strcat('./VGGish/Data_PredScores/Categoty1/',save_filename),"prediction","score")
end
How do I do it for files with no pattern?
I tried to use the ls command:
filename = ls()
But it returns the entire list of file names as a string, without separation.

Faster copyfiles Matlab

I have a folder origin_training with subfolders like FM, folder1, folder2, ... . I can get the list of image files in .png format into a cell called FM.
FM_dir = fullfile(origin_training, 'FM');
FM = struct2cell(dir(fullfile(FM_dir, '*.png')))';
My goal is to match the names in my folder with the images in my cd, and make a new folder FM with the images from cd. Image names in the two paths are identical. I can do that with:
% mother_folder = '...' my current directory
filenames = FM(:,1);
destination = fullfile(mother_folder, 'FM', FM(:,1));
cellfun(#copyfile,filenames, destination);
This is really slow. Takes minutes even for small amounts of images (~30).
My current directory has ~ 10000 images (the ones that correspond to FM, folder2, folder3, ...). What am I missing here?
An alternative would be to create a shell command and execute it. Assuming FM contains full paths for each file, or relative paths from the current directory, then:
FM_dir = fullfile(origin_training, 'FM');
destination = fullfile(mother_folder, 'FM');
curdir = cd(FM_dir);
FM = dir('*.png');
cmd = ['cp ', sprintf('%s ',FM.name), destination];
system(cmd);
cd(curdir);
If you're on Windows, replace 'cp' by 'copy'.
Note that here we're not creating a shell command per file to be copied (presumably what copyfile does), but a single shell command that copies all files at once. We're also not specifying the name for each copied file, we specify the names of the files to be copied and where to copy them to.
Note also that for this to work, mother_folder must be an absolute path.
I somehow put my code into a function and now it works at expected speed. I suspected that cd had to do with the low speed so I am only passing the full directories as character vectors.
The same approach works for my purpose or with a slight modification to just copy from A to B. As now, it works to match files in A to those on B and copy to B/folder_name
function [out] = my_copyfiles(origin_dir, folder_name, dest_dir, extension)
new_dir = fullfile(origin_dir, folder_name);
% Get a cell with filenames in the origin_dir/folder_name
% Mind transposing to have them in the rows
NEW = struct2cell(dir(fullfile(new_dir, extension)))';
dest_folder = fullfile(dest_dir, folder_name);
% disp(dest_folder)
if ~exist(dest_folder, 'dir')
mkdir(dest_folder)
end
%% CAUTION, This is the step
% Use names from NEW to generate fullnames in dest_dir that would match
filenames = fullfile(dest_dir, NEW(:,1));
destination = fullfile(dest_folder, NEW(:,1));
% if you wanted from origin, instead run
% filenames = fullfile(new_dir, NEW(:,1));
% make the copies
cellfun(#copyfile,filenames, destination);
%Save the call
out.originDir = new_dir;
out.copyFrom = dest_dir;
out.to = dest_folder;
out.filenames = filenames;
out.destination = destination;
end

How to read specific images from one folder has different types of images and text files and save into another one

I have a folder with 10 subfolder each has about 100 different files including text files and different extension images. I just need to copy the image files with JPG extension and move it to another single folder.
I am using this code:
clear all
clc
M_dir = 'X:\Datasets to be splitted\Action3\Action3\'% source directory
D_dir = 'X:\Datasets to be splitted\Action3\Depth\'
files = dir(M_dir);% main directory
dirFlags = [files.isdir];
subFolders = files(dirFlags);%list of folders
for k = 1 :length(subFolders)
if any(isletter(subFolders(k).name))
c_dtry = strcat(M_dir,subFolders(k).name)
fileList = getAllFiles(c_dtry)%list of files in subfolder
for n1 = 1:length(fileList)
[pathstr,name,ext] = fileparts(fileList{n1})% file type
%s = dir(fileList{n1});
%S = s.bytes/1000;%file size
Im = imread(fileList{n1});
%[h,w,d] = size(Im);%height width and dimension
if strcmp(ext,'.jpg')|strcmp(ext,'.JPG')%)&S>=50&(write image dimension condition))% here you need to modify
baseFileName = strcat(name,ext);
fullFileName = fullfile(D_dir, baseFileName); % No need to worry about slashes now!
imwrite(Im, fullFileName);
else
end
end
end
end
But the code is stopped with an error when a text file being processed.
The error says:
Error using imread>get_format_info (line 491)
Unable to determine the file format.
Error in imread (line 354)
fmt_s = get_format_info(fullname);
Error in ReadFromSubFolder (line 16)
Im = imread(fileList{n1});
Thanks
Your code is reading the data before you check the extension
Im = imread(fileList{n1});
is before
if strcmp(ext,'.jpg')|strcmp(ext,'.JPG')
edit
For finding files which end 'vis' you can usestrcmp
strcmp ( name(end-2:end), 'vis' )
For completeness you should also check that name is longer than 3 char.
Here is a relatively simpler solution using dir and movefile or copyfile depending on whether you want to move or copy:
%searching jpg files in all subdirectories of 'X:\Datasets to be splitted\Action3\Action3'
file = dir('X:\Datasets to be splitted\Action3\Action3\**\*.jpg');
filenames_with_path = strcat({file.folder},'\',{file.name});
destination_dir = 'X:\Datasets to be splitted\Action3\Depth\';
%mkdir(destination_dir); %create the directory if it doesn't exist
for k=1:length(filenames_with_path)
movefile(filenames_with_path{k}, destination_dir, 'f'); %moving the files
%or if you want to copy then: copyfile(filenames_with_path{k}, destination_dir, 'f');
end

Check wav file exists in Matlab folder

I need to check whether a wav file in Matlab work folder exists ou not. If it does, I need to load the file into a variable (file in my case), i use this code but it doesn't work.
if strcmp(file,'\n')==0
file='test.wav';
elseif findstr(file,'.')==''
file=strcat(file,'.wav');
end
[TestWave,Fs] = audioread(file);
You don't say if you are trying to find a particular .WAV file, or just any .WAV file...
If you just want to know if a particular file (of any kind) exists, use the exist() function. It returns value 2 if a file exits:
myFileName = 'test.wav';
myDirectory = 'c:\temp';
filepath = fullfile(myFileName,myDirectory);
if exist(filepath,'file') == 2
[TestWave,Fs] = audioread(file);
end
Otherwise, just search for the files you need using dir():
myDirectory = 'c:\temp';
wildcard = '*.wav';
theseFiles = dir(fullfile(myDirectory,wildcard));
for i = 1:length(theseFiles)
thisFilePath = fullfile(myDirectory,theseFiles(i).name);
[TestWave,Fs] = audioread(thisFilePath); % Load this file
% Do something with the loaded file...
end

Matlab - open netcdf files from only specific subfolders

I have several subfolders in my parentFolder but I only want to read the .nc files from a few specific subfolders. I thought I had it figured out with this:
parentFolder = '/Users/AM/workspace/';
cd(parentFolder)
s1 = 'daytime/instant';
s2 = 'daytime/monthly';
s3 = 'nighttime/instant';
s4 = 'nightttime/monthly';
sub_f = {s1,s2,s3,s4};
s = strcat(parentFolder, sub_f);
% 1x4 cell with pathnames to files
filePattern = fullfile(s, '*.nc');
ncFiles1 = cell(length(filePattern),1);
for k = 1:4
ncFiles1{k} = dir(filePattern{k});
end
ncFiles = [ncFiles1{1}; ncFiles1{2}; ncFiles1{3}; ncFiles1{4}];
filename = cell(length(ncFiles),1);
for k = 1:length(ncFiles)
filename{k} = ncFiles(k).name;
end
I ended up with a 131x1 cell array of all the filenames I wanted, but when I tried to read the data I got this error message:
Error using internal.matlab.imagesci.nc/openToRead (line 1259)
Could not open instant_SR_CR_DR_2008-07-01T00-15-56ZD_day_CFMIP2_2.90.nc for reading.
I know the files are okay because I can read them in by going to each subfolder individually. Is there a better way to read files out of specific subfolders? Any reason I'm getting that error when I try to open the files?
Thanks in advance!