How to use the current date as name for a CSV file - matlab

How do I create a csv file with date as the name of the csv file. I tried doing it, but the date won't appear only the name does. The language is Scilab which is similar to Matlab.

I do not understand your question fully. But following the csvWrite documentation and the date documentation. You could do someting like this
filename_with_date_string = date() + ".csv";
directory_path = TMPDIR;
// Some matrix you want to save
M = [1:10] * 0.1;
// Create the file
file = fullfile(directory_path, filename_with_date_string);
// Fill it with your matrix
csvWrite(M, file);

Related

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'

Renaming JPG images in matlab

I am new to matlab and image analysis. I would really appreciate some insight/help into the following problem. I am trying to rename images (jpg) in a folder that have a random name into specific (new) names. I made the an excel file with two columns the first column contains the old names and the second column the new names. I found the next code on stack overflow (Rename image file name in matlab):
dirData = dir('*.jpg'); %# Get the selected file data
fileNames = {dirData.name}; %# Create a cell array of file names
for iFile = 1:numel(fileNames) %# Loop over the file names
newName = sprintf('image%05d.jpg',iFile); %# Make the new name
movefile(fileNames{iFile},newName); %# Rename the file
end
The code gives all the photos a new name based on the old one but that is not what I want, the new names I use are not linked to the old ones. I tried the following code :
g= xlsread('names.xlsx') % names.xlsx the excel file with old and new names
for i=1:nrows(g)
image=open(g(i,1));
save(g(i,2),image);
end
It doesn't work. I get the error message :using open (line 68)
NAME must contain a single string. I don't think open is the right function to use.
Thank you !
How about this:
% Get the jpeg names
dir_data = dir('*.jpg');
jpg_names = {dir_data.name};
% Rename the files according to the .xlsx file
[~,g,~] = xlsread('names.xlsx'); % Thanks to the post of Sean
old_names = g(:,1);
new_names = g(:,2);
for k = 1:numel(old_names)
% check if the file exists
ix_file = strcmpi(old_names{k}, jpg_names);
if any(ix_file)
movefile(old_names{k}, new_names{k});
end;
end;
It seems like g = xlsread(file) reads only numeric data from file (see here). The third output argument of xlsread returns raw data including strings; does the following work? (i don't have excel and can't test it)
[~, ~, g] = xlsread('names.xlsx')
for i = 1:nrows(g)
movefile(g{i,1}, g{i,2})
end

MATLAB reading CSV file with timestamp and values

I have the following sample from a CSV file. Structure is:
Date ,Time(Hr:Min:S:mS), Value
2015:08:20,08:20:19:123 , 0.05234
2015:08:20,08:20:19:456 , 0.06234
I then would like to read this into a matrix in MATLAB.
Attempt :
Matrix = csvread('file_name.csv');
Also tried an attempt formatting the string.
fmt = %u:%u:%u %u:%u:%u:%u %f
Matrix = csvread('file_name.csv',fmt);
The problem is when the file is read the format is wrong and displays it differently.
Any help or advice given would be greatly appreciated!
EDIT
When using #Adriaan answer the result is
2015 -11 -9
8 -17 -1
So it seems that MATLAB thinks the '-' is the delimiter(separator)
Matrix = csvread('file_name.csv',1,0);
csread does not support a format specifier. Just enter the number of header rows (I took it to be one, as per example), and number of header columns, 0.
You file, however, contains non-numeric data. Thus import it with importdata:
data = importdata('file_name.csv')
This will get you a structure, data with two fields: data.data contains the numeric data, i.e. a vector containing your value. data.textdata is a cell containing the rest of the data, you need the first two column and extract the numerics from it, i.e.
for ii = 2:size(data.textdata,1)
tmp1 = data.textdata{ii,1};
Date(ii,1) = datenum(tmp1,'YYYY:MM:DD');
tmp2 = data.textdata{ii,2};
Date(ii,2) = datenum(tmp2,'HH:MM:SS:FFF');
end
Thanks to #Excaza it turns out milliseconds are supported.

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);

tab delimited text file from matlab

The following code generates a similar dataset to what I am currently working with:
clear all
a = rand(131400,12);
DateTime=datestr(datenum('2011-01-01 00:01','yyyy-mm-dd HH:MM'):4/(60*24):...
datenum('2011-12-31 23:57','yyyy-mm-dd HH:MM'),...
'yyyy-mm-dd HH:MM');
DateTime=cellstr(DateTime);
header={'DateTime','temp1','temp2','temp4','temp7','temp10',...
'temp13','temp16','temp19','temp22','temp25','temp30','temp35'};
I'm trying to convert the outputs into one variable (called 'Data'), i.e. have header as the first row (1,:), 'DateTime' starting from row 2 (2:end,1) and running through each row, and finally having 'a' as the data (2:end,2:end) if that makes sense. So, 'DateTime' and 'header' are used as the heading for the rows and column respectively. Following this I need to save this into a tab delimited text file.
I hope I've been clear in expressing what I'm attempting.
An easy way, but might be not the fastest:
Data = [header; DateTime, num2cell(a)];
filename = 'test.txt';
dlmwrite(filename,1); %# no create text file, not Excel
xlswrite(filename,Data);
UPDATE:
It appears that xlswrite actually changes the format of DateTime values even if it writes to a text file. If the format is important here is the better and actually faster way:
filename = 'test.txt';
out = [DateTime, num2cell(a)];
out = out'; %# our cell array will be printed by columns, so we have to transpose
fid = fopen(filename,'wt');
%# printing header
fprintf(fid,'%s\t',header{1:end-1});
fprintf(fid,'%s\n',header{end});
%# printing the data
fprintf(fid,['%s\t', repmat('%f\t',1,size(a,2)-1) '%f\n'], out{:});
fclose(fid);