The typical use case is to check paths at the start of a script/function before saving/exporting, with human readable feedback if validation fails.
tf = isvalidpath( inputPath )
checks if the platform can parse the path inputPath
. Unlike isfolder
and isfile
, it does not verify that the path exists in the file system.
tf = isvalidpath( inputPath, pathType )
also checks that the location of inputPath
is either a file or directory.
tf = isvalidpath( inputPath, "file", validExtensions )
also checks that inputPath
contains a file extension from a provided set, validExtensions
.
[ tf, Log ] = isvalidpath( __ )
additionally returns formatted log messages. Log.warning
explains why a path is not valid. Log.info
provides formatting tips. Use the disp
function to print the log to the command window.
mustBeValidPath( inputPath, pathType, validExtensions )
function identically to isvalidpath
but throws an error if the path format is not valid. pathType
and validExtensions
are optional.
Argument | Description |
---|---|
inputPath |
Path to validate.
|
pathType |
Valid location type of inputPath . Either:
|
validExtensions |
Specifies which file extensions are valid if the input is a file path. Each entry must be either:
|
Argument | Description |
---|---|
tf |
Whether the path valid or not according to the above options. Logical scalar. |
Log |
Formatted log messages. Struct scalar with the fields:
Log will be "" , i.e., a zero length string. Use the disp function to print the messages to the command window, e.g., disp( Log.warning ) . |
load( "spine.mat", "X" )
X = X / max( X, [], "all" );
outputFile = "output\xray.jpg";
validExts = ["" ".mat" "image"];
[ isSave, Log ] = isvalidpath( outputFile, "file", validExts );
if isSave
[ filePath, ~, fileExt ] = fileparts( outputFile );
if ~isfolder( filePath )
[ status, msg ] = mkdir( filePath );
assert( status == 1, ...
"Could not make output directory:\n -\t%s", msg )
end
try
if strcmp( fileExt, "" ) || strcmp( fileExt, ".mat" )
save( outputFile, "X" )
else
imwrite( X, outputFile )
end
fprintf( "Saved patient scan to '%s'.\n", outputFile )
catch ME
warning( ME.identifier, ...
"Patient scan not saved:\n -\t%s", ME.message )
end
else
warning( "Patient scan not saved. " + ...
"outputFile is not a valid.\n\n%s\n", Log.warning )
end
Created in 2022b. Compatible with MATLAB release 2019b and later. Compatible with all platforms.
Published under MIT License (see LICENSE.txt).
Please cite George Abrahams (GitHub, LinkedIn, Google Scholar).