How to save figures using mkdir if paths are variables?

16 views (last 30 days)
I am trying to save all of my figures into a directory that is generated using the date and time of running the code as the filename. The figures are being saved to a folder in a different directory. I would like to use mkdir to create the folders but I do not know how to get mkdir to read strings assinged to variables that contain the paths I want to save the figures to. My current directory is C:\Users\a\b\c\d\e\workspace but I want to save the figures to 'C:\Users\a\b\c\d\e\figures\dateTimeFolderName'. My final save folder structure should be 'C:Users\.....\figures\16-May-2022 13:41:03.617'. Is there a way to do this using mkdir?
savedir = 'C:\Users\a\b\c\d\e\figures\dateTimeFolderName'
startTime = 16-May-2022 13:41:03.617; % this is a date and time array that is produced when my code is run
if savefigs==1
mkdir savedir startTime
end

Accepted Answer

Steven Lord
Steven Lord on 16 May 2022
Edited: Steven Lord on 16 May 2022
Functions in MATLAB that accept text data can be called in one of two ways: command form or function form. Let me show you each of these forms for a function with which you may be familiar that accepts text data: help. I'll call it in three ways that are equivalent: one in command form and two in function form.
help pi % command form
PI 3.1415926535897.... PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897.... Documentation for pi doc pi
help('pi') % function form
PI 3.1415926535897.... PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897.... Documentation for pi doc pi
n = 'pi';
help(n) % also function form
PI 3.1415926535897.... PI = 4*atan(1) = imag(log(-1)) = 3.1415926535897.... Documentation for pi doc pi
When you call the function in command form you don't need to use parentheses or wrap the text in quotes, but what you pass in will literally be accepted as that text. So if I tried to use command form with the variable n I defined above, it won't work.
help n % This will NOT show the help for the pi function
n is a variable of type char.
Rather than using command form to call mkdir, use function form like the third line of the example above.
Oh, you should also look at the fullfile function. It will help you assemble your path string.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by