I am running the following script to create pdf file.
%% Plotting confusion matrix
if(opt == 1)
plotconfusion_mod(y(:,1:2)',y(:,3:4)');
elseif(opt == 2)
plotconfusion_mod(y(:,1:4)',y(:,5:8)');
elseif(opt == 3)
plotconfusion_mod(y(:,1:10)',y(:,11:20)');
set(gcf,'position',[100, -100, 800, 800])
end
set(gcf,'Units','inches'); screenposition = get(gcf,'Position');
set(gcf,'PaperPosition',[0 0 screenposition(3:4)],'PaperSize',screenposition(3:4));
%% Saving
Q = input('Do you want to save the results (Y/N)\n','s');
if(Q == 'y' || Q == 'Y')
print(1,['confusion_matrix_' num2str(opt)],'-dpdf','-r512');
else
return
end
But I am getting the following error on Windows operating system.
Error using name (line 102)
Cannot create output file '.\snippet_1.pdf'.
Error in print (line 85)
pj = name( pj );
Can anyone help with it please?
The value of opt is 1.
Given the comments, the problem is due to the OP accessing a directory without permissions. Several answers might be appropriate in this case but likely require knowing more about the system (Linux, Windows, Mac, which directory, etc.). However, I feel like the easiest way to avoid such hassles is to simply move your code into a sub-directory that is in your HOME directory.
HOME directory might mean different things depending on your system, but it is usually the one that contains your "documents" folder.
If you do not want to move the codebase for some reason, you wil require assistance with changing permissions and are best off asking in system-specific forum or with system-specific tags.
Related
I'm trying to open images with imread but it keEps telling me that the files do not exist.
Here's the message from the command window
Error using imread>get_full_filename (line 516)
File "Pic1.jpg" does not exist.
Error in imread (line 340)
fullname = get_full_filename(filename);
Error in ImageDetection (line 2)
img1 = imread('Pic1.jpg');
And here are the sections of code that it's referencing from the function itself
if (fid == -1)
if ~isempty(dir(filename))
% String 'Too many open files' is from strerror.
% So, no need for a message catalog.
if contains(errmsg, 'Too many open files')
error(message('MATLAB:imagesci:imread:tooManyOpenFiles', filename));
else
error(message('MATLAB:imagesci:imread:fileReadPermission', filename));
end
else
error(message('MATLAB:imagesci:imread:fileDoesNotExist', filename));<--LINE 516
end
if isempty(fmt_s)
% The format was not specified explicitly.
% Get the absolute path of the file
fullname = get_full_filename(filename); <--LINE 340
Image isn't in Current Directory (Or Path)
If your image is in your working directory, you can call it by its name ("Pic1.jpg"). However, MATLAB doesn't search all folders on your computer. If, for example, if your program is running in C:\Users\user\Documents\MATLAB, and the image is in C:\Users\user\Pictures, you could reference the picture using:
Absolute paths ("C:\Users\user\Pictures\Pic1.jpg")
Relative paths ("..\..\Pictures\Pic1.jpg")
Usually, if the pictures only exist because of your program, it'd be somewhere in the same directory, so you wouldn't need to use ".." to move up any directories.
If you want the user to be able to select a picture each time the program is run, I'd recommend looking into uigetfile. If you want to know more about where MATLAB searches for files, see this article.
Secondly, you may want to check your file name. While it seems obvious, a simple misspelling can be hard to notice at times, for example "Pic1.jpg" vs "Pic1,jpg" vs "Pic1.jpeg"
Just above the line of your code where the error occurs, write a new line:
dir
To output in the prompt the files of the current folder, and check that the name of your file exactly appears there. Could you copy us that output?
Don't know why this isn't working anymore. Very simple. I have a script with a folder in the same path. The folder contains a series of m files for the script to work.
Originally I simply would use
addpath('.../utilities/);
when the script was first run. but recently I started receiving this error
Warning: Name is nonexistent or not a directory: ...\utilities
In path (line 109)
In addpath (line 88)
In Myrunningcode (line 101)
and I don't know why.
I fixed the problem by running the following code
p = mfilename('fullpath');
[filepath,~,~] = fileparts(p);
addpath([filepath,'/utilities/']);
At least I would like to know why this error occurred.
Here is my directory setup. I use windows 10 and matlab 2016a.
The issue is likely that your current directory (pwd) is not the same as the file location. The relative directory isn't relative to the current script, it's relative to pwd, hence why the mfilename workaround fixes your issue.
The first solution is your own, but you can do it in one line:
addpath( fullfile( fileparts( mfilename('fullpath') ), 'utilities' ) );
Then the quickest way to check if your files are already on the path is using which:
% Assuming that myFile.m is within the utilities folder, and not shadowed elsewhere.
% If utilities is on the path, which('myFile') will not be empty.
if isempty( which( 'myFile' ) )
addpath( fullfile( fileparts( mfilename('fullpath') ), 'utilities' ) );
end
Alternatively, you could pair the above check with a persistent flag variable, so you don't have to repeat the check if you re-enter the function.
Note that addpath isn't particularly slow, it's genpath you want to avoid if you were to add a load of subdirectories too.
Aside: It's good to use fullfile instead of manually concatenating with (OS dependent) file separators. Less room for error (e.g. double slashes) even if you're always using the same OS.
The correct way to include a relative folder is:
addpath('./utilities/');
with a single dot.
This has worked (and works) since the existence of relative folders, AFAIK, so you should be able to use it without fear of deprecation
This is a script written by someone else, and I don't understand why it is giving me this error (I don't really know Matlab, but this appears to be a fairly straightforward script, so I'm a bit stumped).
The file starts with
clear all
filein=['Runs/'];
Namein1=['AIC'];
Nameout=['Nash'];
It then does a bunch of calculations to get Nash-Sutcliffe coefficients (not important for this issue) and then tries to write the results to one file:
%Write Nash
%Output file writing
%Write file header
D={'Conbination','Nash with Error','Nash-error','RMSE','RMSE-error',...
'AIC', 'MinNash', 'MaxNash'};
NameOut=[filein,Nameout, '.txt'];
fileID = fopen(NameOut,'w');
for i=1:length(D)-1
fprintf(fileID,'%s\t',D{i});
Then more stuff follows, but this is where I get the error message:
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in Nash_0EV_onlyT (line 169)
fprintf(fileID,'%s\t',D{i});
I don't get what is wrong here? The script specifies the file, and uses fopen...? Isn't it supposed to create the file Nash.txt with the fopen statement (this file currently does not exist in my folder Runs/)? What am I missing? Thanks!
PS I am running Matlab2013a (group license via the university) on a MacBook Pro with OSX 10.8
Try using fclose all before calling this script again. Often when testing, the file handle is never released (an error occurs before the file is closed), causing fopen on the same file to fail.
The better way to do this would be to use a more fail-safe construct:
NameOut = [filein Nameout '.txt'];
fileID = fopen(NameOut,'w');
if fileID > 0
try
for i = 1:length(D)-1
fprintf(fileID,'%s\t',D{i});
end
fclose(fileId);
catch ME
fclose(fileId);
throw(ME);
end
else
error('Error opening file.');
end
I am running Win 10 and matlab 2015a, but it happens in mine too.
finally, I realise that the matlab.exe can't write file in the folder /../bin/
so, change to
Nameout=['C:\Users\yourname\DesktopNash'];
try it, then tell me what' going on.
Okay, so as I said, I don't know Matlab... I hadn't properly specified the path for writing! So it was reading the input but I guess didn't know where to write to. Thanks for the answers, it did help me narrow down the problem!
sometimes I load a .m file to work in the workspace, but I usually forget what is the recent file I´ve opened. So in the same way that you write who and you can see the variables of the workspace I suppose there should be a command to know what is the .m file in which you are working.
Does anyone know a command like this?
Thank you so much.
For newer MATLAB versions, there is a way to get the fullpath of the file currently being edited in the Editor:
if verLessThan('matlab', '7.10')
%# not supported
fname = '';
elseif verLessThan('matlab', '7.12')
%# R2010a,R2010b: editorservices
fname = editorservices.getActiveFilename;
else
%# R2011a: matlab.desktop.editor API
fname = matlab.desktop.editor.getActiveFilename;
end
mfilename seemed to be the right choice, but it returns an empty string when called from the command line. Therefore you may check the 'command history' provided by the IDE.
For larger projects it most often makes sense to use MATLAB's object model or at least functions in order to structure your work. Working in the 'workspace' often results in unwanted side effects.
I do something like this to bootstrap runs:
%%
params.run = 'hairy.m';
params.hair = 10;
setup_defaults(params);
run_lots_of_code(params);
This has advantages as it hides the 'globals' in a single global (params), and the global tells you where they came from.
I run MATLAB on both Linux and Windows XP. My files are synced among all of the computers I use, but because of the differences in directory structure between Linux and Windows I have to have separate import and export lines for the different operating systems. At the moment I just comment out the line for the wrong OS, but I am wondering if it is possible to write something like:
if OS == Windows
datafile = csvread('C:\Documents and Settings\Me\MyPath\inputfile.csv');
else
datafile = csvread('/home/Me/MyPath/inputfile.csv');
end
This is also a more general question that applies in cases where one wants to execute system commands from within MATLAB using system('command').
You can use ispc/isunix/ismac functions to determine the platform or even use the computer function for more information about the machine
if ispc
datafile = csvread('C:\Documents and Settings\Me\MyPath\inputfile.csv');
else
datafile = csvread('/home/Me/MyPath/inputfile.csv');
end
To follow up on Amro's answer, I was going to just make a comment but struggled with the formatting for the code.
I'd prefer to split the OS selection from the file read.
if ispc
strFile = 'C:\Documents and Settings\Me\MyPath\inputfile.csv';
else
strFile = '/home/Me/MyPath/inputfile.csv';
end
try
datafile = csvread(strFile);
catch
% setup any error handling
error(['Error reading file : ',strFile]);
end
That way if I need to change the way the file is read, perhaps with another function, it's only one line to change. Also it keeps the error handling simple and local, one error statement can handle either format.
Just to add a minor point to the existing good answers, I tend to use fileparts and fullfile when building paths that need to work on both UNIX and Windows variants, as those know how to deal with slashes correctly.
In addition to using the various techniques here for dealing with path and file separator differences, you should consider simply trying to avoid coding in absolute paths into your scripts. If you must use them, try to put them in as few files as possible. This will make your porting effort simplest.
Some ideas:
Set a fileRoot variable at some early entry point or config file. Use fullfile or any of the other techniques for constructing a full path.
Always use relative paths, relative to where the user is operating. This can make it easy for the user to put the input/output wherever is desired.
Parameterize the input and output paths at your function entries (e.g., via a system specific context object).
If the directory structures are within your home directory you could try building a single path that can be used on both platforms as follows (my Matlab is a bit rough so some of the syntax may not be 100%):
See here for how to get the home directory for the user
Create the path as follows (filesep is a function that returns the file separator for the platform you are running on)
filepath = [userdir filesep 'MyPath' filesep 'inputfile.csv']
Read the file
datafile = csvread(filepath)
Otherwise go with Amros answer. It is simpler.