Save a workspace with current time. MAtlab - matlab

I would like to save all simulation variables ad fig with the current time.
my solution:
t = datetime('now','Format','dd-MM-yyyy''_T''HHmmss');
t2 = datevec(t);
DateString = datestr(t2);
filename=[DateString,' all_variables_main '];
save(filename )
savefig(filename)
The following error was given in Matlab:
Unable to write file 26-Oct-2019 09:47:15 all_variables_main : Invalid argument.
What have I done wrong?

mat filenames cannot have spaces or colons in them. You can use the following to directly obtain the date and time in a format that is allowed in a filename:
>> fileName = [datestr(now, 'dd-mmm-yyyy_HHMMSS') '_all_variables_main']
fileName =
'26-Oct-2019_103123_all_variables_main'
>> save(fileName)

File name containing : character is not a valid file name.
You can replace the : with "꞉" character.
See: How to get a file in Windows with a colon in the filename?
You can replace all : with ꞉ character (unicode character A789 that looks like colon) that is valid to be used in file name.
filename(filename == ':') = char(hex2dec('A789'));
Make sure to use the right character when loading the file.
Remark: The above solution was tested in Windows 10, and MATLAB R2016a.

Related

Having trouble conditionally moving files based on their names

I am trying to write a script that will auto sort files based on the 7th and 8th digit in their name. I get the following error: "Argument must be a string scalar or character vector". Error is coming from line 16:
Argument must be a string scalar or character vector.
Error in sort_files (line 16)
movefile (filelist(i), DirOut)
Here's the code:
DirIn = 'C:\Folder\Experiment' %set incoming directory
DirOut = 'C:\Folder\Experiment\1'
eval(['filelist=dir(''' DirIn '/*.wav'')']) %get file list
for i = 1:length(filelist);
Filename = filelist(i).name
name = strsplit(Filename, '_');
newStr = extractBetween(name,7,8);
if strcmp(newStr,'01')
movefile (filelist(i), DirOut)
end
end
Also, I am trying to make the file folder conditional so that if the 10-11 digits are 02 the file goes to DirOut/02 etc.
First, try avoid using the eval function, it is pretty much dreaded as slow and hard to understand. Specially if you need to create variables. Instead do this:
filelist = dir(fullfile(DirIn,'*.wav'));
Second, the passage:
name = strsplit(Filename, '_');
Makes name a list, so you can access name{1} or possibly name{2}. Each of these are strings. But name isn't a string, it is a list. extractBetween requires a string as an input. That is why you are getting this problem. But note that you could have simply done:
newStr = name(7:8);
If name was a string, which in Matlab is a char array.
EDIT:
Since it has been now claimed that the error occurs on movefile (filelist(i), DirOut), the likely cause is because filelist(i) is a struct. Wheres a filena name (char array) should have been given at input. The solution should be replacing this line with:
movefile(fullfile(filelist(i).folder, filelist(i).name), DirOut)
Now, if you want to number the output folders too, you can do this:
movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,name(7:8)])
This will move a file to /DirOut/01. If you wanted /DirOut/1, you could do this:
movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,int2str(str2num(name(7:8)))])

Saving figure without providing filename [duplicate]

this question about matlab:
i'm running a loop and each iteration a new set of data is produced, and I want it to be saved in a new file each time. I also overwrite old files by changing the name. Looks like this:
name_each_iter = strrep(some_source,'.string.mat','string_new.(j).mat')
and what I#m struggling here is the iteration so that I obtain files:
...string_new.1.mat
...string_new.2.mat
etc.
I was trying with various combination of () [] {} as well as 'string_new.'j'.mat' (which gave syntax error)
How can it be done?
Strings are just vectors of characters. So if you want to iteratively create filenames here's an example of how you would do it:
for j = 1:10,
filename = ['string_new.' num2str(j) '.mat'];
disp(filename)
end
The above code will create the following output:
string_new.1.mat
string_new.2.mat
string_new.3.mat
string_new.4.mat
string_new.5.mat
string_new.6.mat
string_new.7.mat
string_new.8.mat
string_new.9.mat
string_new.10.mat
You could also generate all file names in advance using NUM2STR:
>> filenames = cellstr(num2str((1:10)','string_new.%02d.mat'))
filenames =
'string_new.01.mat'
'string_new.02.mat'
'string_new.03.mat'
'string_new.04.mat'
'string_new.05.mat'
'string_new.06.mat'
'string_new.07.mat'
'string_new.08.mat'
'string_new.09.mat'
'string_new.10.mat'
Now access the cell array contents as filenames{i} in each iteration
sprintf is very useful for this:
for ii=5:12
filename = sprintf('data_%02d.mat',ii)
end
this assigns the following strings to filename:
data_05.mat
data_06.mat
data_07.mat
data_08.mat
data_09.mat
data_10.mat
data_11.mat
data_12.mat
notice the zero padding. sprintf in general is useful if you want parameterized formatted strings.
For creating a name based of an already existing file, you can use regexp to detect the '_new.(number).mat' and change the string depending on what regexp finds:
original_filename = 'data.string.mat';
im = regexp(original_filename,'_new.\d+.mat')
if isempty(im) % original file, no _new.(j) detected
newname = [original_filename(1:end-4) '_new.1.mat'];
else
num = str2double(original_filename(im(end)+5:end-4));
newname = sprintf('%s_new.%d.mat',original_filename(1:im(end)-1),num+1);
end
This does exactly that, and produces:
data.string_new.1.mat
data.string_new.2.mat
data.string_new.3.mat
...
data.string_new.9.mat
data.string_new.10.mat
data.string_new.11.mat
when iterating the above function, starting with 'data.string.mat'

How to put conversion operation in a for loop?

Below is the code to convert .tim file to ascii file for one particular file. But what I need is to convert 500 files(.tim). I also need to save the .ascii file in SAME name as the .tim file name like below for all 500 files.
bin=fopen('file_01.tim','r');
ascii = fread(bin, [43,21000], 'float32');
data_values=ascii';
dlmwrite('file_01.xls', data_values, 'delimiter', '\t', ...
'precision', '%.6f','newline','pc');
Using a "for loop" to do the conversion and save the ascii file with the same name of the tim, was my first thought but I don't know how to that.
You can use dir to get a list of all the filenames in your folder and then proceed just as you have but using replacing 'file_01.tim' with [D(ii).name]
e.g.
D = dir('*.tim');
for ii = 1:size(D,1)
bin=fopen(D(ii).name,'r');
%your processing etc
savename = [strtok(D(ii).name,'.'), '.xls']; %Change the file ext from .tim to .xls
dlmwrite(savename, ...
 

Naming a file in matlab

I currently have this:
[filename, pathname, filterindex] = uiputfile({...
... (various filetypes)
'Disks image.jpg');
if isequal(filename,0) || isequal(pathname,0)
disp('User selected Cancel');
else
disp(['User selected ',fullfile(pathname,filename)]);
end
imwrite(M, 'Disks image.jpg', 'jpg');
disp('Image saved');
end
How would I write for the part currently saying 'Disks image.jpg' a name that is either the current time (given by the following):
dateTime = javaMethod('currentTimeMillis', 'java.lang.System');
Or a name that is a combination of both that and some other specified name (e.g. currentTimeMillis_Diffraction_pattern.jpg)
As I am saving two image files, it would be good if I can name the file by the second method, as it gives an ordered list without having to separate the two images into different file folders.
Using time...........+..........._Diffraction_pattern.extension would be great
Thanks
Not sure why you are using a Java function to get the time, rather than built in Matlab time function. I would just use
dateTimeString = datestr(now, 'yyyy-mm-dd-HH_MM_SS_FFF');
Then concatenate that with whatever name you want to create a file name:
myFileName = [dateTimeString '_withSomeName.jpg'];
imwrite( M, myFileName, 'jpg' );
Note - I think that if you include the .jpg extension on the file, it will automatically be converted by imwrite so you don't need the third argument. Also note that using the FFF format specifier will give you the time down to ms - so it's got the same functionality (and granularity) as your original Java function call, but results in more sensible file names.
If you insist on using the Java function, you need to convert it to Matlab's internal clock - this means something like this (untested):
timeNow = javaMethod('currentTimeMillis', 'java.lang.System');
timeMatlab = timeNow / (1000 * 3600 * 24) + datenum('1 Jan 1970');
dateTimeString = datestr(timeMatlab, 'yyyy-mm-dd-HH_MM_SS');
but why would you do that...
String concatenation can be done like this:
filename=[num2str(dateTime) '_Diffraction_pattern.extension'];
Or using sprintf:
filename=sprintf('%d_Diffraction_pattern.extension',dateTime);

Matlab Read Text File List Exclude first 34 characters

I am trying to read values from a text file. I want the value after ': '.
Here is a sample of the text file. All lines are formated the same.
There are 34 places before the start of the data.
File Name : IMG_1184.JPG
File Size : 2.1 MB
File Modification Date/Time : 2012:07:14 11:53:18-05:00
File Permissions : rw-rw-rw-
File Type : JPEG
MIME Type : image/jpeg
Exif Byte Order : Big-endian (Motorola, MM)
I tried to use this code:
fileID = fopen('Exif.txt');
Exif1 = textscan(fileID, '%s %s','delimiter', ':');
This worked on most of the data but some data also used ':' so that didn't work.
I tried to use this code:
fileID = fopen('Exif.txt');
Exif1 = textscan(fileID, '%s %s','delimiter', ': ');
This returned a mess. Not sure why. Everything was fragmented.
Can anyone explain how to just get the 35th value to the end of every string and put it into an array?
There is the function strtrim(string) in Matlab which will strip the leading and trailing spaces for you. Try reading the data in a line at the time into the textscan function after using strtrim?
Read the whole line into a variable then get the 35th and subsequent characters like this:
whole_line(35:end)