Matlab verification of file after copy - matlab

I would like to know whether we have a way using matlab to check the integrity of a file after copying to another folder.
I have 8 files in folder A. I will copy them in detination folder B. But at the end I want to verify that the copied files in folder B are exactly the same (size, integrity, data in the file) of the original file in folder A.

You could run a system command to compute a checksum & then parse it out from the captured output. It would depend on your OS which command would be appropriate.
The code below should get you started. I included examples for Windows and a little bit for Linux. However since I don't have my Linux Box turned on I didn't include any code to parse the cksum values from the system output.
if ispc
srcCmd = sprintf('CertUtil -hashfile %s MD5',fullPathToSourceFile);
dstCmd = sprintf('CertUtil -hashfile %s MD5',fullPathToDestFile);
[stat_S,cmdout_S] = system(srcCmd);
[stat_D,cmdout_D] = system(dstCmd);
parsed_S = textscan(cmdout_S,'%s','delimiter','\n');
MD5_S = parsed_S{1}{2};
parsed_D = textscan(cmdout_D,'%s','delimiter','\n');
MD5_D = parsed_D{1}{2};
if strcmp(MD5_S,MD5_D)
disp('MD5 Good :)')
else
disp('MD5 Bad :(')
end
elseif isunix
srcCmd = sprintf('cksum %s',fullPathToSourceFile);
dstCmd = sprintf('cksum %s',fullPathToDestFile);
[stat_S,cmdout_S] = system(srcCmd);
[stat_D,cmdout_D] = system(dstCmd);
%Insert parsing & checking code for Linux
end

Here is another way to check your files, it's kind of 'manually', we just open two files and check the data. MD5 check must be faster, but in my viewpoint, it would be changed accidentally when we view&save the file without changing.
clc; clear;
fA=dir('E:/folderA');
fB=dir('E:/folderB');
for i=1:length(fA)
pos=find(cellfun(#(x)isequal(x,fA(i).name),{fB.name}));
if (fA(i).isdir == 1 || isempty(pos))
continue;
end
%open file in FolderA
fid=fopen(['E:/folderA/' fA(i).name],'r');
dataA=fread(fid,inf,'char');
fclose(fid);
%open file in FolderB
fid=fopen(['E:/folderB/' fA(i).name],'r');
dataB=fread(fid,inf,'char');
fclose(fid);
%Isequal
if (isequal(dataA,dataB))
disp(['file ' fA(i).name ' is exactly the same.'])
else
%print something
end
end

Related

While running Compiled MatLab from console window, prompt returns immediately while app is still running

I have compiled my simple MatLab function so I can run it from a Windows console as a command line app. After I enter the command and its single argument, the prompt returns immediately even though the command is still running, as if running in the background.
Can someone tell me why this happens and how do I stop it? I'd like it to behave like a normal application and not return to the prompt until complete.
EDIT: Sorry I didn't post the code previously, I figured I was making a common mistake and would get a quick answer. Anyway, here it is.
It translates a .mat file to a .csv file and then runs another console command via "system" to perform a quick edit on the resulting .csv file. Several minutes of IO but not much else.
I've never compiled MatLab before so probably something simple, I hope.
function WriteMatToCSV( inFile, overWrite )
if ~exist(inFile, 'file')
fprintf('Error File not found: %s\n',inFile);
return;
end
overWriteExisting = 1;
if exist('overWrite','var')
overWriteExisting = overWrite;
end
% Change file extension
outFile = strrep( inFile, '.mat','.csv');
fprintf('In : %s\n',inFile);
fprintf('Out: %s\n',outFile);
% Overwrite if exists?
if exist(outFile, 'file')
if ~overWriteExisting
fprintf('Error File exists: %s\n',outFile);
return;
end
end
% Get variable name in the file
matObj = matfile(inFile);
info = whos(matObj);
name = info.name;
fprintf('Found variable: %s\n',name);
% Load the variable from the file
fprintf('Loading mat...\n');
load(inFile);
% Write the variable to .csv file
fprintf('Writing csv...\n');
export(eval(name),'File',outFile','Delimiter',',');
fprintf('Rewriting to remove MatLab bits...\n');
command = 'RewriteMatLabCSV';
command = [command ' ' outFile];
[status,cmdout] = system(command,'-echo');
fprintf(cmdout);
fprintf('Done\n');
end

Search and replace variable

I have some 100+ conf files that I am working. I need to find and replace various variable for all these files. For example, I'd like to find the line
Amplitude = 100; and replace it to: Amplitude = 200; for all files.
I've searched in online and found the solution only for one file. I'm looking for a way to do that in Matlab. Any ideas?
If these files can be opened as normal text files then I wouldn't use matlab. Notepad++ has an replace option for as many files as you want, just make sure, you test it out on a backup file first. so have it find "Amplitude = 100" and replace that by what you want.
To see how to do it, look here:
how-to-find-and-replace-lines-in-multiple-files
If you can't do that, put all the files in the same directory (you have to do this anyway). Then load the files in matlab with that directory and run a for loop. However it might be a bit slow./
Basically if you can do 1 file, you could do all of them with a for loop.
If you need help with that I show can some code I used before.
Well, Matlab solution would be to (recursively) open all files in the directory. Here I show example for non-recursive solution (it does not check subfolders), though it would be easy enough to modify it to search subfolders too if needed:
d = dir(yourPath);
for i = 1 : length(d)
if ~(d(i).isdir)
%d(i) is file.
replaceSingleFile(strcat(d(i).folder, d(i).name));
end
end
As you say, you already know how to do replace for a single file, though to have complete answer here, solution could be along the lines (in the function replaceSingleFile).
F = fopen(fileYouWantReplaced);
i = 1;
while (~feof(F))
L = fgetl(F);
L = strrep(L, 'Amplitude = 100;', 'Amplitude = 200;');
Buf{i} = L;
i = i + 1;
end
fclose(F);
%now just write all Buf to the same file again.
F = fopen(file..., 'w'); % Discard contents.
for i = 1 : numel(Buf)
fprintf(F, '%s\n', Buf{i});
end
fclose(F);

read image permission in Matlab

I'm trying to access images in a matlab interface
my code is as follows:
global im2 im
axes(handles.axes4);
[path1, user_cance]= imgetfile();
if user_cance
msgbox(sprintf('Error'), 'Error', 'Error');
return
end
srcFiles = dir('C:\Users\User\Desktop\images test\yale faces\yalefaces\..');
% yale faces is the database folder
for i = 1 : length(srcFiles)
file_name=dir(strcat('C:\Users\User\Desktop\images test\yale faces\yalefaces'));
im2=imread(strcat('C:\Users\User\Desktop\images test\yale faces\yalefaces',file_name(i).name));
%processing of read image
end
the issue is that when I run the code, it gives the following error:
Can't open file "C:\Users\User\Desktop\images test\yale faces\yalefaces" for
reading;
you may not have read permission.
Does anyone know how to solve this issue?
When you do a directory listing (without any wildcards) you are going to get the current directory '.' and parent directory as well '..'. You can't read these like files because they are directories. You will need to filter out the directories prior to trying to read them with imread.
files = dir('C:\Users\User\Desktop\images test\yale faces\yalefaces');
% Remove directories
files = files(~[files.isdir]);
As a side note, it is very hard to tell what your code is doing, but I'm pretty sure it doesn't do what you hope.
It seems like you want to get all images within the database. If that's so, you'll want to do something like.
folder = 'C:\Users\User\Desktop\images test\yale faces\yalefaces';
% Get a list of all files in this folder
files = dir(folder);
files = files(~[files.isdir]);
for k = 1:numel(files)
% Append the folder with the filename to get the path and load
im2 = imread(fullfile(folder, files(k).name));
end
I highly discourage using strcat to construct file paths particularly because it removes trailing/leading whitespace from each input which can corrupt a filename. fullfile was designed for exactly this so please use that.

text scan iterations

I have some files to process , but i have missing files in middle
i am using
for i=1:file;
fid = fopen(['Raw',num2str(i),'.txt']);
D = textscan(fid1,'%*f %f%*f%*f%*f%f%f%[^\n]','delimiter',';', 'headerlines',50,'CollectOutput', 1);
fclose(fid);
Now the rest of program works well when i have files in order
i.e, 100,200 any number of files in my folder in order as Raw1.txt, Raw2.txt, Raw3.txt, ....
I get into trouble as soon as there are missing files like Raw1.txt, Raw4.txt, Raw5.txt
How do i iterate my text scan so it can ignore the file numbering?
Thanks
Edit :
By missing files i mostly mean numbers after 'Raw'
My files get generated as Raw1, Raw2, Raw3............ Raw400.txt
When all the files are in order and present i have no problem.
when i have some missing or jumps like for example
Raw1 . Raw2.......... Raw10, Raw15, Raw16
I have trouble as there is jump from Raw10.txt to Raw15.txt
I have same problem if my files start at anything other than Raw1.txt
look for exist in matlab documentation. Something like this should work:
for i=1:file;
if exist(['Raw',num2str(i),'.txt'], 'file')
% File exists!
fid = fopen(['Raw',num2str(i),'.txt']);
D = textscan(fid1,'%*f %f%*f%*f%*f%f%f%[^\n]','delimiter',';', 'headerlines',50,'CollectOutput', 1);
fclose(fid);
end
end
Note that exist(Name, 'file') checks for the file's directory too, so either give the full file name (i.e. with path), or try something like if exist(Name, 'file') == 2

MATLAB - read files from directory?

I wish to read files from a directory and iteratively perform an operation on each file. This operation does not require altering the file.
I understand that I should use a for loop for this. Thus far I have tried:
FILES = ls('path\to\folder');
for i = 1:size(FILES, 1);
STRU = pdbread(FILES{i});
end
The error returned here suggests to me, a novice, that listing a directory with ls() does not assign the contents to a data structure.
Secondly I tried creating a file containing on each line a path to a file, e.g.,
C:\Documents and Settings\My Documents\MATLAB\asd.pdb
C:\Documents and Settings\My Documents\MATLAB\asd.pdb
I then read this file using the following code:
fid = fopen('paths_to_files.txt');
FILES = textscan(fid, '%s');
FILES = FILES{1};
fclose(fid);
This code reads the file but creates a newline where a space exists in the pathway, i.e.
'C:\Documents'
'and'
'Setting\My'
'Documents\MATLAB\asd.pdb'
Ultimately, I then intended to use the for loop
for i = 1:size(FILES, 1)
PDB = pdbread(char(FILES{i}));
to read each file but pdbread() throws an error proclaiming that the file is of incorrect format or does not exist.
Is this due to the newline separation of paths when the pathway file is read in?
Any help or suggestions greatly apppreciated.
Thanks,
S :-)
First Get a list of all files matching your criteria:
( in this case pdb files in C:\My Documents\MATLAB )
matfiles = dir(fullfile('C:', 'My Documents', 'MATLAB', '*.pdb'))
Then read in a file as follows:
( Here i can vary from 1 to the number of files )
data = load(matfiles(i).name)
Repeat this until you have read all your files.
A simpler alternative if you can rename your files is as follows:-
First save the reqd. files as 1.pdb, 2.pdb, 3.pdb,... etc.
Then the code to read them iteratively in Matlab is as follows:
for i = 1:n
str = strcat('C:\My Documents\MATLAB', int2str(i),'.pdb');
data = load(matfiles(i).name);
% use our logic here
% before proceeding to the next file
end
I copy this from yahoo answers! It worked for me
% copy-paste the following into your command window or your function
% first, you have to find the folder
folder = uigetdir; % check the help for uigetdir to see how to specify a starting path, which makes your life easier
% get the names of all files. dirListing is a struct array.
dirListing = dir(folder);
% loop through the files and open. Note that dir also lists the directories, so you have to check for them.
for d = 1:length(dirListing)
if ~dirListing(1).isdir
fileName = fullfile(folder,dirListing(d).name); % use full path because the folder may not be the active path
% open your file here
fopen(fileName)
% do something
end % if-clause
end % for-loop