I am saving the contents of an array to different files as follows:
for i=1:10
name = [myfilename num2str(i)]
savevar = myvariable(i)
filename = mat2str([name '.dat'])
save(filename, savevar, '-ascii','-double','-append')
end
I have been fiddling around with this for a while and keep getting the following error:
??? Error using ==> save
Argument must contain a string.
Where am I going wrong?
The arguments of the save command must be strings. Specifically, the second argument must be a string that contains the variable name.
The problem in your case is that savevar is the actual value of the variable, and not its name.
I'm not really getting what type of variable you're trying to save. If it's a matrix, you're just better off saving it as a whole to a single file, like so:
save(filename, 'myvariable', '-ascii', '-double', '-append')
and if you have numerous variables, and you want each variable in a different file (which is a bit closer to your example), I suggest you create a cell array of the variable names:
varname = {'A', 'B', 'C', ...} % # Assuming A, B, C, etc. are actual variables
and then use it in the save command inside a loop:
save(filename, varname{i}, '-ascii', '-double', '-append')
Related
I'm trying to save list of variables from the workspace into a .mat file. The problem I encountered is that I'm trying to make a function of it, and that function should be able to handle a list of variables to be saved. I could loop as below:
vars = {'a','b','c'}; % names of variables
for k = 1:numel(vars)
save(filename,vars(k),'-append');
end
but this is not elegant for me and the flag -append slowed down the process.
I'm trying to achieve something like this:
vars = {'a','b','c'}; %names of variables
save(filename,vars);
Is this possible?
Since save expects each variable name as a separate input argument, you can use a comma-separated list generated from the cell array:
save(filename, vars{:})
The filename in question is a MAT file that contains elements in the form of "a - bi" where 'i' signifies an imaginary number. The objective is to separate the real, a, and imaginary, b, parts of these elements and put them into two arrays. Afterwards, a text file with the same name as the MAT file will be created to store the data of the newly created arrays.
Code:
function separate(filename)
realArray = real(filename)
imagArray = imag(filename)
fileIDname = strcat(filename, '.txt')
fileID = fopen(fileIDname, 'w')
% more code here - omitted for readability
end
I am trying to run the above code via command window. Here's what I've tried so far:
%attempt 1
separate testFileName
This does not work as the output does not contain the correct data from the MAT file. Instead, realArray and imagArray contains data based on the ascii characters of "testFileName".
e.g. first element of realArray corresponds to the integer value of 't', the second - 'e', third - 's', etc. So the array contains only the number of elements as the number of characters in the file name (12 in this case) instead of what is actually in the MAT file.
%attempt 2
load testFileName
separate(testFileName)
So I tried to load the testFileName MAT variable first. However this throws an error:
Complex values cannot be converted to chars
Error in strcat (line 87)
s(1:pos) = str;
Error in separate (line xx)
fileIDname = strcat(filename, '.txt')
Basically, you cannot concatenate the elements of an array to '.txt' (of course). But I am trying to concatenate the name of the MAT file to '.txt'.
So either I get the wrong output or I manage to successfully separate the elements but cannot save to a text file of the same name after I do so (an important feature to make this function re-usable for multiple MAT files).
Any ideas?
A function to read complex data, modify it and save it in a txt file with the same name would look approximately like:
function dosomestuff(fname)
% load
data=load(fname);
% get your data, you need to knwo the variable names, lets assume its call "datacomplex"
data.datacomplex=data.datacomplex+sqrt(-2); % "modify the data"
% create txt and write it.
fid=fopen([fname,'.txt'],'w');
fprintf(fid, '%f%+fj\n', real(data.datacomplex), imag(data.datacomplex));
fclose(fid);
There are quite few assumptions on the data and format, but can't do more without extra information.
I have different mat files w/ distinct names. So I am using a function whose input is the mat file. I used "varargin" to enable the function to take different files.
function bestfunc(varargin)
data = load(varargin, '-mat');
end
when I try to call the function like
bestfunc('matrix777')
Matlabe comes up w/ this error:
Error using load
Argument must contain a string.
Any ideas?
you have to get the names of the files. You can use dir() to do that.
dir('*.mat') % will return information about all .mat files in the folder
The output is a struct with more information for each file. TO get the names try
names=struct2cell(dir('*.mat'));
names=names(1,:);
now names is a cellarray with the names of all *.mat files of your folder. TO load data from each go for
for i=1:length(names)
bestfun(names{i});
end
Since you're only passing one argument, you don't need varargin, which is used when you may have a variable number of arguments to a function.
Just use a normal variable name like matname:
function bestfunc(matname)
data = load(matname, '-mat');
end
Then call it as you did before:
bestfunc('matrix777')
I have 31 models an I want to save each one in a specific file
this is my matlab function
formatspec='model%d'
for k = 1:length(libsvmFiles)
baseFileName = libsvmFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
[labels train]=libsvmread(fullFileName);
model=svmtrain(labels,train, '-t 2 -h 0');
file=sprintf(formatspec,k);
save file model;
but the problem is only the first file is saved and its name is 'file' tha's mean the value of the variable file is not evaluated
how can I solve this problem ?
As many Matlab functions, save can be used in function form (save(...)) or in command form (save ...). In the command form that you use, all the arguments are interpreted as strings. That means
save file model
is equivalent to
save('file', 'model')
For the second argument that is correct, because you want to refer to the variable with the name "model". For the first argument it is wrong, because you want to refer to the file name contained in the variable file. The correct syntax to use is therefore
save(file, 'model')
You're missing the parens for the save function. The model variable also needs to be listed as a string since you need to tell the save function the name of the variable, not the variable itself. See Matlab's documentation.
save(file, 'model');
Additionally you don't have an end to your for loop shown, which normally would just throw an error -- however later code might cause this loop to instead only run once. Otherwise you should check your libsvmFiles variable as it might be only length 1 or not be an array.
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>