I have a script that pulls one file at a time from my current working directory and plots specified information. I would like to save each of the plots as a jpeg (tiff is okay too) with the name of the file it's plotting. I have about 3000 files, so I am looking for an automated way to do this.
I thought this might work if placed at the end of the for-loop:
saveas(gcf, ' ',jpg)
I am not sure what to put in quotations for the file name.
Example
The plot of the data in data1.mat should be saved in the file data1.jpeg
If loadedFileName is the name (and perhaps) path of the file that you just loaded, then you could do something like the following to save the jpeg with the same file name
% get the path, name and extension of the file just loaded
[path, name, ext] = fileparts(loadedFileName);
% grab what you want to create the filename of the jpeg to save
jpegToSaveFileName = [name '.jpg']; % use path if you want to save to same directory
% save the figure as a jpeg
saveas(gcf,jpegToSaveFileName,'jpg');
Try the above and see what happens. If you need to add a path to the file name, then do something like
jpegToSaveFileName = fullfile(path, jpegToSaveFileName);
Try the above and see if it does what you need!
Since your script already has the information of the filenames (otherwise it could not open the files and read the data), you could just extend the filename with '.jpg' and pass this string to the saveas function. Demo for filename 'hello':
>> filename = 'hello'
filename =
hello
>> picname = [filename, '.jpg']
picname =
hello.jpg
>> a = figure
a =
4
>> saveas(a, picname)
>> ls
hello.jpg
Related
This is probably a simple question, but I have some files and data. After printing each one of them to a '-dpng' file, I just want to view the plot and copy them elsewhere. However, opening the file, all I see is the "Import Wizard". I click "Finish" and nothing happens. This is my code:
files = dir('*.csv');
for file = files'
lab5 = csvread(file.name, 9)
lab5(:,1) = log10(lab5(:,1))
plot(lab5(:,1),lab5(:,2))
print(strcat(file.name,'plot'), '-dpng')
end
I tried to avoid print() by using savefig, but for some reason savefig was giving me a vague error. Only print works, but I'm not sure how to view the output.
You are saving your image as filename.csvplot, which Preview does not accept as a valid image file.
For example:
% Generate dummy file
fID = fopen('blah.csv', 'w');
fclose(fID);
% Recreate print job
files = dir('*.csv');
plot(1:10)
fname = strcat(files(1).name, 'plot');
print(fname, '-dpng');
Which gives us:
fname =
blah.csvplot
Why isn't .png appended to the filename? Per the documentation for print:
If the file name does not include an extension, then print appends the appropriate one.
Filename inputs are parsed for an extension (e.g. things prepended with .), and does not append an extension if one is found. In this case, the filename passed to print has the .csvplot extension. This might be unexpected but it does make sense, file extensions don't actually control anything about the file itself; you could save your file as image.finderpleaseopen and have it still be a valid PNG file. Finder is just too stubborn to open it without being forced because it's not a known, supported file extension.
To fix this, you should save your file with the correct file extension. There are two ways to do this, append the correct extension or remove the undesired extension with something like fileparts or regexprep and let print handle it for you.
For example:
% blah.csvplot.png
fname = strcat(files(1).name, 'plot', '.png');
print(fname, '-dpng');
% blahplot.png
[~, filename] = fileparts(files(1).name);
fname = strcat(filename, 'plot');
print(fname, '-dpng');
savefig does not produce a valid output for Finder because it does not produce any output without a .fig extension:
If the specified file name does not include a .fig file extension, then MATLAB appends the extension. savefig does not accept other file extensions.
*.fig files are not image files and cannot be opened natively by finder.
I have a lot of .fig files that are named like this: 20160922_01_id_32509055.fig, 20160921_02_id_53109418.fig and so on.
So I thought that I create a script that loop through all the .fig files in the folder and group(copy) them into another folder(s) based on the last number in the file name. The folder is created based on the id number. Is this possible?
I have been looking on other solutions involving looping through folders but I am totally fresh. This would make it easier for me to check the .fig files while I am learning to do other stuff in Matlab.
All is possible with MATLAB! We can use dir to get all .fig files, then use regexp to get the numeric part of each filename and then use copyfile to copy the file to it's new home. If you want to move it instead, you can use movefile instead .
% Define where the files are now and where you want them.
srcdir = '/my/input/directory';
outdir = '/my/output/directory';
% Find all .fig files in the source directory
figfiles = dir(fullfile(srcdir, '*.fig'));
figfiles = {figfiles.name};
for k = 1:numel(figfiles)
% Extract the last numeric part from the filename
numpart = regexp(figfiles{k}, '(?<=id_)\d+', 'match', 'once');
% Determine the folder we are going to put it in
destination = fullfile(outdir, numpart);
% Make sure the folder exists
if ~exist(destination, 'dir')
mkdir(destination)
end
% Copy the file there!
copyfile(fullfile(srcdir, figfiles{k}), destination)
end
Here's an example how to identify and copy the files. I'll let you do the for loop :)
>> Figs = dir('*.fig'); % I had two .fig files on my desktop
>> Basename = strsplit(Figs(1).name, '.');
>> Id = strsplit(Basename{1}, '_');
>> Id = Id{3};
>> mkdir(fullfile('./',Id));
>> copyfile(Figs(1).name, fullfile('./',Id));
Play with the commands to see what they do. It should be straightforward :)
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.
I am using the FileExchange code cell2csv to save a cell in my code. I'd like the output file, the csv file, to be saved to a different directory. How can that be done?
Here's my current code for saving the cell:
cell2csv([fname(13:16), '-', u_id{k}, '_24hrBlkAvg.csv'], site_data, '\t'); % cell2csv(filename,cellArray,delimiter)
you can use fullfile to construct your path in a system-independent way
%// do not put everything in one line, the code should be readable to human:
filename = [fname(13:16), '-', u_id{k}, '_24hrBlkAvg.csv']
filepath = fullfile(beetroot_folder, daughter_folder, subsubfolder, filename)
cell2csv(filepath, site_data, '\t');
if you need to save in a subfoder, use '.' for your current folder,
or for saving in a sister folder use '..' for parent folder:
filepath = fullfile('.', filename)
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