Auto generate a name when saving file in Matlab? - matlab

I am working on a GUI and I have a file named 'work.mid'. The user can make some modifications to it and when they click the save button I want it to be saved as 'work1.mid' to 'c:\saved_datas\'. When they click that button second time, it should save it as 'work2.mid', on the third time 'work3.mid' and so on. Here's the code I have so far:
nmat = readmidi_java('work.mid');
Name = fullfile('c:\saved_datas\', '?????');
writemidi_java(nmat, Name);
Figuring out what should go at ????? is where I'm stuck.

The following code would work if you have no prior work*.mid or if you have any number of sequential work*.mid files inside c:\saved_datas\. Now, if the files are not in sequence, this code could be tweaked for that, just let me know if you would like to handle that case too.
Code listed here -
%// Parameters
org_filename = 'work.mid';
main_dir = 'c:\saved_datas\'; %//'
%// Your code
nmat = readmidi_java(org_filename);
%// Added code
[~,filename_noext,ext] = fileparts(org_filename)
filenames = ls(strcat(main_dir,filename_noext,'*',ext))
new_filename = strcat(filename_noext,num2str(size(filenames,1)+1),ext)
Name = fullfile(main_dir,new_filename)
%// Your code
writemidi_java(nmat, Name);
For achieving uniqueness of filenames, some also use timestamps. This could be implemented like this -
org_filename = 'work.mid'; %//'
main_dir = 'c:\saved_datas\'; %//'
[~,filename_noext,ext] = fileparts(org_filename)
new_filename = strcat('filename_noext','-',datestr(clock,'yyyy-mm-dd-hh-MM-SS'),ext)
Name = fullfile(main_dir,new_filename);

This could be done a couple of ways depending on how you have structured your GUI. You need to keep track of how many times the button has been pressed. In the callback for the button you could use a persistent variable ('count') and increment it by one at the start of the function. Then construct the filename with filename = ['work' num2str(count) '.mid']. Alternatively you could increment a class member variable if you have implemented your GUI using OOP.
To save the file use the 'save()' function with the previously constructed file name and a reference to the variable.
Check out the documentation for persistent variables, save, fullfile and uiputfile for extra info.

Related

naming and saving workspace variables to a file with a changing number in the name - Matlab

So the output of my code produce many variables in every loop in Matlab workspace. I want to save two of the variables (namely MO and Vr) to a file having a fixed name with a number which change in every loop. The number which changes in each loop is "NT+1".
First I change the name of the two desired variables with following code:
eval(sprintf('MO%d=MO;',NT+1));
eval(sprintf('Vr%d=Vr;',NT+1));
Now I want to save the renamed MO and Vr variables in a .mat file having the NT+1 number at the end. For instance, if NT+1=60, I want the the two renamed variables (which are MO60 and Vr60) be saved in a file having the NT+1 number at the end: sim60.mat
save('sim%d.mat','MO%d','Vr%d',NT+1)
hypothetical, the output of the above code should be a file named 'sim60.mat' having the two variables MO60 and Vr60.
How can I automatically perform such saving when the NT+1 changes in every loop and the name of MO and Vr also must be changed for the save command at each loop?
You should not rename the workspace variables because you will need to use eval, which is almost always bad practice.
Go with
% create file name
flNm = num2str(i,'sim%d.mat');
% save file
save(flNm,'MO','Vr');
if you now load the file, load it to a struct
flNm = num2str(i,'sim%d.mat');
Dat = load(flNm,'MO','Vr');
% access the variables
Dat.Mo
Dat.Vr
usually one needs to load and save variables within a loop because the memory is too small to store them in a multidimensional array or a cell:
i_max = 10;
MO_all = NaN(3,3,i_max)
Vr_all = cell(i_max)
for i = 1:i_max
% what happens in every loop
MO = rand(3,3);
Vr = rand(randi(10),randi(10)); % changing size
% store for other loops
MO_all(:,:,i) = MO;
Vr_all{i} = Vr;
end
The solution to you particular question is
(I do not recommend using this as it is not flexible, not robust and requires eval to create the variables in the first place!)
flNm = num2str(NT+1,'sim%d.mat');
vars2save = {num2str(NT+1,'MO%d'),num2str(NT+1,'Vr%d')};
save('sim%d.mat',vars2save {:})

How to perform processinng on .csv files used by my code for each person in one go without defining functions for each person in Matlab?

I have a main code named as process.m in which I define the path to 4 different .csv files for calculating values for each person. If I have a list of 30 persons and I don't want to define process.m as a function for each person, how can I do the processing for all the persons in one go. I want some idea by which process.m itself picks files for one person, then generate the results, then move to other person, pick his .csv files, generate the result and so on.
A breif outline of my code is attached here that would project the problem.
file1='Joseph_front.csv';
file2='Joseph_side.csv';
file3='Joseph_knee.csv';
file4='Joseph_back.csv';
A1=initiate2(file1); %initiate2 function reads the csv and perfoms some filtering operations on image in .csv format
A2=initiate2(file2);
A3=initiate2(file3);
A4=initiate2(file4);
%%omitted large part of code
cal(1) = p+q+r*s;
cal(2) = p+q+r+s;
cal(3) = p+q+r-s;
cal=cal'
%code to write the calculation in excel file
excelfile= 'test.xlsx';
xlswrite(excelfile,ValuesInInches,'Joseph_data',posColumn);
Describing more i want my code to process for 30 people all at once by selecting and picking the files itself, although i have done this operation by making the same code as a function for each person, but that is not very efficient as when I have to make a small change I have to make it in every function that means one change needs to be edited in 30 functions. Please suggest an efficient way to do it.
Note: All persons .csv files are named in the same manner and exist in the current folder.
I am assuming all of your files in one directory and there's no other files .
This portion of code will get the available filenames.
listFiles = dir('path of the directory');
filenames = strings; % an empty string array to save the filenames
j = 1;
for i = 1:1:length(listFiles)
if ~listFiles(i).isdir % to avoid the directory names
filenames(j,1) = listFiles(i).name;
j = j+1;
end
end
Now, there's 4 file for each person. So the loop should take 4 files at a time.
for ii = 1:4:length(filenames)
file1=filename(i);
file2=filename(i+1);
file3=filename(i+2);
file4=filename(i+3);
%% continue with your code
end

Sequential import of datafiles according to rule in Matlab

I have a list of .txt datafiles to import. Suppose they are called like that
file100data.txt file101data.txt ... file109data.txt I want to import them all using readtable.
I tried using the for to specify a vector a = [0:9] through which matlab could loop the readtable command but I cannot make it work.
for a = [0:9]
T_a_ = readtable('file10_a_data.txt')
end
I know I cannot just put _a_ where I want the vector to loop through, so my question is how can I actually do it?
Thank you in advance!
Here is a solution that should work even if you have missing files in your folder (e.g. you have file100data.txt to file107data.txt, but you are missing file file108data.txt and file109data.txt):
files=dir('file10*data.txt'); %list all data files in your folder
nof=size(files,1); %number of files
for i=1:nof %loop over the number of files
table_index=files(i).name(7) %recover table index from data filename
eval(sprintf('T%s = readtable(files(i).name)', table_index)); %read table
end
Now, please note that is it generally regarded as poor practice to dynamically name variables in Matlab (see this post for example). You may want to resort to structures or cells to store your data.
You need to convert the value of a into a string and combine strings together, like this:
Tables = struct();
for a = 0:9
% note: using dynamic structure field names to store the imported tables
fname = ['file10_' num2str(a) '_data'];
Tables.(fname) = readtable([fname '.txt']);
end

Matlab - using a function mulitple times in the same workspace, to add values and fields to a structure

I have a structure such as:
specimen.trial1 = 1
I now want to add another trial to the specimen, so that
specimen.trial1 = 1
specimen.trial2 = 2
I can do this without a problem within the workspace and command window. But, if I'm using a function to calculate the numbers for each trial (with dynamic fields), the new field and value erases the previous one. Eg:
function [specimen] = dummy(trial,value)
specimen.(trial) = value
end
run the function:
[specimen] = dummy('trial1',1)
then run the function again with different inputs, but keeping the structure intact in the workspace
[specimen] = dummy('trial2',2)
Instead of getting a structure with 2 fields, I get just one with Trial2 being the only field. Does that make any sense? What would like is to use the outputs of a function to progressively add to a structure.
Thank you,
Chris
Yes it makes sense, because you're creating a new struct specimen within your function.
Solution: pass the the previous specimen to the function as well.
function [specimen] = dummy(specimen,trial,value)
specimen.(trial) = value
end
and call:
[specimen] = dummy(specimen,'trial1',1)
or alternativly leave out the assignment at all and use the following
function [output] = dummy(value)
output = value
end
and call:
[specimen.trail1] = dummy(1)
which really depends on what you actually want to do. Put passing a name to a function which uses this name to define a struct is a little pointless unless you "use" that name otherwise. Also if you want to have input-dependent dynamic names you'd also go with the first alternative

Matlab: dynamic name for structure

I want to create a structure with a variable name in a matlab script. The idea is to extract a part of an input string filled by the user and to create a structure with this name. For example:
CompleteCaseName = input('s');
USER WRITES '2013-06-12_test001_blabla';
CompleteCaseName = '2013-06-12_test001_blabla'
casename(12:18) = struct('x','y','z');
In this example, casename(12:18) gives me the result test001.
I would like to do this to allow me to compare easily two cases by importing the results of each case successively. So I could write, for instance :
plot(test001.x,test001.y,test002.x,test002.y);
The problem is that the line casename(12:18) = struct('x','y','z'); is invalid for Matlab because it makes me change a string to a struct. All the examples I find with struct are based on a definition like
S = struct('x','y','z');
And I can't find a way to make a dynamical name for S based on a string.
I hope someone understood what I write :) I checked on the FAQ and with Google but I wasn't able to find the same problem.
Use a structure with a dynamic field name.
For example,
mydata.(casename(12:18)) = struct;
will give you a struct mydata with a field test001.
You can then later add your x, y, z fields to this.
You can use the fields later either by mydata.test001.x, or by mydata.(casename(12:18)).x.
If at all possible, try to stay away from using eval, as another answer suggests. It makes things very difficult to debug, and the example given there, which directly evals user input:
eval('%s = struct(''x'',''y'',''z'');',casename(12:18));
is even a security risk - what happens if the user types in a string where the selected characters are system(''rm -r /''); a? Something bad, that's what.
As I already commented, the best case scenario is when all your x and y vectors have same length. In this case you can store all data from the different files into 2 matrices and call plot(x,y) to plot each column as a series.
Alternatively, you can use a cell array such that:
c = cell(2,nufiles);
for ii = 1:numfiles
c{1,ii} = import x data from file ii
c{2,ii} = import y data from file ii
end
plot(c{:})
A structure, on the other hand
s.('test001').x = ...
s.('test001').y = ...
Use eval:
eval(sprintf('%s = struct(''x'',''y'',''z'');',casename(12:18)));
Edit: apologies, forgot the sprintf.