How do you view the plots saved by the print() function in Matlab? - matlab

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.

Related

Taking symbolic variables out of txt file and making a matrix in Matlab

I have a txt file containing following characters.
theta1 , l1 and others are symbolic variables.( Don't mind about it)
M=[theta1 + (l1^2*m1)/4 + l1^2*m2 (l1*l2*m2*cos(fi1 - fi2))/2 ;
(l1*l2*m2*cos(fi1 - fi2))/2 theta2 + (l2^2*m2)/4 ]
I need to take it out and make it a symbolic matrix. As you can see txt file is already fine for making matrix but I don't want to copy paste the whole thing to script, I rather want to do it automatically.
fid = fopen('a.txt');
MMatrix=textscan(fid,'%s');
fclose(fid);
I tried the code above but it turn out to be not useful. What do you think is the way to copy the whole thing and use it for matrix making?
Instead of reading that as a string or a character array and then possibly resorting to evil (eval) method, just rename the extension from txt to m since you already have your arrays defined in the MATLAB way in the text files. Maintain a backup copy of those original txt files if needed.
If it is a single file (a.txt), you can rename it manually or with this code to a.m:
movefile('a.txt', 'a.m');
If there are multiple such files in a directory then you can use the following code to change the extension of all such txt files in the current directory:
txtfiles = dir('*.txt'); %getting all txt files in the current directory
for num = 1:numel(txtfiles)
[~, fname] = fileparts(txtfiles(num).name); %filename (without extension)
movefile(txtfiles(num).name, [fname,'.m']); %renaming
end
Now you can simply use the name of the respective file in your script to get whatever arrays that file have in it.

Reading a file from a different directory in matlab

My matlab function is in a folder that contains the main project and the other functions of the code. However, the data is stored in a folder withing the main one named "data" and inside the specific dataset that i want, for example "ded4" in this example. I can't figure out how to open the text file that I want without changing the file to the main folder. The code I have so far is:
function[Classify] = Classify(logDir)
%%%%logDir='ded014a04';
Directory = ['data/' logDir '/']
Filename = [logDir '-fixationsOffSet']
File_name = fullfile(Directory,Filename)
File = fopen(File_name,'r')
end
The code is in the 'dev' folder, I think my path is correct because when I do
open(File_name)
it opens.
Thanks for the help
If you want to open the file in the editor, use
open(File_name)
If you want to read data from the file, you can use
dlmread(File_name) % Read ASCII delimited file.
or
C = textscan(File,'FORMAT') % Read formatted data from text file or string.
or more low-level using fscanf, e.g., if the file contains three columns of integers you do the following: Read the values in column order, and transpose to match the appearance of the file: (from the help of fprintf)
fid = fopen('count.dat');
A = fscanf(fid,'%d',[3,inf])';
fclose(fid);

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.

Saving figure with current file name in MatLab

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

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