Saving Multiple Arrays to Text File in Matlab - matlab

I need to save multiple arrays to a text file with the filename the same as the variable name. I have created a vector of all the variables required using the follow lines.
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
end
end
I am now struggling to find a way to save all of these variable to file. Any help would be appreciated.
Thank you

I'm not sure if I understood correctly. Do you want to save each variable in different files? Assuming you want to save all variables in the same file with, lets say, the first value of the vector as the filename, you could try something like:
filename = sprintf('vector_starting_with%d.mat', vars(1).name);
save(filename)
In case you want separated files for each element in the vector, you could try:
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
varsave=sprintf('vector_%d.mat', vars(i).name)
save(varsave);
end
end
Sorry that it might have some bugs, right now I don't have MATLAB. Nevertheless, try to go over this documentation.
Edit Let me know if you try this then:
all_var={};
vars=whos;
for(i=1:size(vars,1))
if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
all_var{end+1}=vars(i).name;
filename = sprintf('%d.txt', vars(i).name);
file = fopen(filename,'w');
fprintf(file,vars(i).name);
fclose(file);
end
end

Related

Octave: create .csv files with varying file names stored in a sub folder

I have multiple arrays with string data. All of them should be exported into a .csv file. The file should be saved in a subfolder. The file name is variable.
I used the code as follows:
fpath = ('./Subfolder/');
m_date = inputdlg('Date of measurement [yyyymmdd_exp]');
m_name = inputdlg('Characteristic name of the expteriment');
fformat = ('.csv');
fullstring = strcat(fpath, m_date,'_', m_name, fformat);
dlmwrite(fullstring,measurement);
However, I get an error that FILE must be a filename string or numeric FID
What's the reason?
Best
Andreas
What you are asking to do is fairly straightforward for Matlab or Octave. The first part is creating a file with a filename that changes. the best way to do this is by concatenating the strings to build the one you want.
You can use: fullstring = strcat('string1','string2')
Or specifically: filenameandpath = strcat('./Subfolder/FixedFileName_',fname)
note that because strings are pretty much just character arrays, you can also just use:
fullstring = ['string1','string2']
now, if you want to create CSV data, you'll first have to read in the file, possibly parse the data in some way, then save it. As Andy mentioned above you may just be able to use dlmwrite to create the output file. We'll need to see a sample of the string data to have an idea whether any more work would need to be done before dlmwrite could handle it.

Loading multiple .mat files containing the same variable name and changing the variable names simultaneously?

So I have a directory that has many .mat files:
apples.mat, oranges.mat, bananas.mat, grapes.mat, apricots.mat, pears.mat, pineapple.mat
All of these .mat files has a variable name "calories" assigned a value. How do I load all of these .mat files simultaneously in MATLAB and change the variables for each one from calories to calories_(fruit name) so that I can have all the variable values in the workspace to play with?
For example, I want to load apples.mat and change its variable name from calories to calories_apple, then load oranges.mat and change is variable name from calories_orange, etc. without doing it all manually.
I know it's something along the lines of creating a string with the different fruit names, and the indexing along the string to load a file and change its variable from variable to variable_%s with the %s indicating the fruit content generated along the loop. It's a big mess for me, however, I don't think I'm structuring it right. Would anyone care to help me out?
I would load each .mat file in sequence and put each of the corresponding calories as a separate field being all combined into a single struct for you to access. Given the directory of where these .mat files appear, do something like this:
%// Declare empty structure
s = struct()
folder = '...'; %// Place directory here
%// Get all MAT files in directory
f = dir(fullfile(folder, '*.mat'));
%// For each MAT file...
for idx = 1 : numel(f)
%// Get absolute path to MAT file - i.e. folder/file.mat
name = fullfile(folder, f(idx).name);
%// Load this MAT file into the workspace and get the calories variable
load(name, 'calories');
%// Get the name of the fruit, are all of the characters except the last 4 (i.e. .mat)
fruit_name = f(idx).name(1:end-4);
%// Place corresponding calories of the fruit in the structure
s.(['calories_' fruit_name]) = calories;
end
You can then access each of the calories like so using dot notation:
c = s.calories_apple;
d = s.calories_orange;
...
...
... and so on.
I am assuming that you do not mean to include the parenthesis in calories_(fruit name). I am also assuming there are no other .mat files in your current directory. This should do the trick:
theFiles = dir('*.mat');
for k = 1:length(theFiles)
load(theFiles(k).name, 'calories');
eval(['calories_' theFiles(k).name(1:length(theFiles(k).name)-4) ' = calories;'])
clear calories
end
Let me know if this helps or not.
EDIT
As, rayryeng points out. The use of eval is, apparently, a bad practice. So, if you are willing to change the way you are thinking about the problem, I suggest you use a structure. In which case, rayryeng's response would be an acceptable answer, even though it does not directly answers your original question.

Find and replace text file Matlab

I'm writting a Matlab code that generates an array number and it should replace that each number in a text file (that already exists) and replace all instances with that. The number should be in string format. I've achieved this:
ita='"';
for i=1:size(z,2)
word_to_replace=input('Replace? ','s');
tik=input('Replacement? ','s');
coluna=input('Column? ');
files = dir('*.txt');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w');
val=num2str(z(i,coluna));
word_replacement=strcat(tik,val,ita);
contents = regexprep(contents,'word_to_replace','word_replacement');
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end
end
I want the code to open the file#1 ('file.txt'), find and replace all instances 'word_replacement' with 'word_to_replace' and save to the same file. The number of txt files is undefined, it could be 100 or 10000.
Many thanks in advance.
The problem with your code is the following statement:
contents = regexprep(contents,'word_to_replace','word_replacement');
You are using regular expressions to find any instances of word_to_replace in your text files and changing them to word_replacement. Looking at your code, it seems that these are both variables that contain strings. I'm assuming that you want the contents of the variables instead of the actual name of the variables.
As such, simply remove the quotations around the second and third parameters of regexprep and this should work.
In other words, do this:
contents = regexprep(contents, word_to_replace, word_replacement);

saving all variable values in matlab's workspace together with their names

I'd like to save print all my variables in my workspace to a file together with their names in a certain way:
%<*firstVariableName>firstVariableValue(s)%</firstVariableName>
%<*secondVariableName>secondVariableValue(s)%</secondVariableName>
I'd like to save each variable on a new line. I've experimented with the function who, but I can't seem to get it to work.
I also have problem getting it to save as UTF-8, is there a simple encoding setting that could be changed?
The who function will save the names of the variables, but not the data in the variables. If you'd like to save the actual variables, you should use the save function, and save it to a *.mat file.
If you're trying to get a list of the names of the variables formatted in a certain way, I'd recommend doing this:
varlist = who(variables);
varlist is a cell array. You can then fopen to start writing to a file, iterate through the cell array using fwrite, and fclose it when you're done. By the way, when you iterate, you should use varlist{x}, which will return the string (whereas varlist(x) will return the cell).
Hope this helps. :)
This may not work in all cases, but it works well for numeric inputs. It may be modified appropriately as per your use case:
%Clears current workspace.
clear;
%Sample data.
a = 1;
b = [2 3];
new_var = [4;5];
%Relevant code.
my_var_list = who;
fid = fopen('my_var_list.txt','w');
for my_var_ii=1:numel(my_var_list)
my_temp_var = eval(my_var_list{my_var_ii});
my_temp_str = cellstr(strcat(sprintf('%%<*%s>', my_var_list{my_var_ii}), num2str(my_temp_var(:)'), sprintf('%%</%s>', my_var_list{my_var_ii})));
fprintf(fid, '%s\n', my_temp_str{:});
end
fclose(fid);
clear fid;
clear my_temp_var;
clear my_var_ii;
clear my_var_list;
clear my_temp_str;
Now my 'my_var_list.txt' will contain:
%<*a>1%</a>
%<*b>2 3%</b>
%<*new_var>4 5%</new_var>

MATLAB - printing graph with different output names

I have a MATLAB program that graphs some things and then outputs the graph to a file. If I run this program several times in the same directory, the file gets overwritten each time. How can I make it so the filename it outputs to changes...
I currently have this:
print -depsc myfigure
I have strings, rate and name, that I want to use, but can't get anything to work. If I can't use my strings, something random would be fine as well. Any way to do this?
Many thanks!
Name it with the current date and time:
print('-depsc2', ['prefix_' datestr(now, 30)])
run right now in PST, this creates a file called prefix_20100220T200733.eps. You can obviously change the prefix and/or the date format.
You can add current time to your file name. For example:
m=magic(10);
fh=figure, surf(m);
currenttime= datestr(now,'MMSSFFF');
print(['-f',num2str(fh)],'-depsc',['outputFileName_',currenttime,'.eps']);
This code checks if file exists, and if yes, adds a counter to its name.
filename = 'myfigure';
if exist([filename '.eps'],'file')
k=1;
while exist([filename '_' num2str(k) '.eps'], 'file')
k=k+1;
end
filename = [filename '_' num2str(k)]);
end
print('-depsc', filename);
Its simple. worked for me.
currenttime= datestr(now,'dd-mm-yy_HH:MM')
filename= ['graph' currenttime '.jpg']
print('-dpdf',filename)
Or any other file format you want to export. check print help.