How to use append command in matlab? - matlab

I want to save data into a .mat file. When I add data for a second time it overwrites the previously stored content. I used the following command but is not working:
save('newAnswer.mat','dat','-append');
with
newAnswer.mat -> matFileName
dat -> arrayName

The '-append' option adds a new variable to the file. If you want to save the same variable, it will update the existing value of the variable in the file. If you think of it, makes sense—you can't have two variables with the same name in workspace, so you can't have two variables with the same name in the .mat file.
The workarounds are at least two: either 1) copy your variable in a new one, and save that variable:
dat1 = dat;
save('newAnswer.mat','dat1','-append');
or 2) create a cell array of values for each new value that you want to save, and update that variable:
%'before everything else'
dat_history = {};
%'. . .'
dat_history{end+1} = dat;
save('newAnswer.mat','dat_history','-append');

Related

Save multiple variables from a list of names in one go without using loop

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{:})

MATLAB: Save figure with default name

I am running a matlab-script that produces a figure. To save this figure I use:
print(h_f,'-dpng','-r600','filename.png')
What this means is that if I don't change filename for each time I run the script, the figure filename.png will be overwritten.
Is there a way to save a figure to a default name, e.g. untitled.png, and then when the script is run twice it will make a new figure untitled(1).png instead of overwriting the original one?
You could create a new filename based on the number of existing files
defaultName = 'untitled';
fileName = sprintf('%s_%d.png', defaultName, ...
length(dir([defaultName '_*.png'])));
print(h_f,'-dpng','-r600', fileName)
Add a folder path to your dir search path if the files aren't located in your current working directory.
This will create a 0-index file name list
untitled_0.png
untitled_1.png
untitled_2.png
untitled_3.png
...
You could also use tempname to generate a long random name for each iteration. Unique for most cases, see section Limitations.
print(h_f,'-dpng','-r600', [tempname(pwd) '.png'])
The input argument (pwd in the example) is needed if you do not want to save the files in your TEMPDIR
You can try something like this:
for jj=1:N
name_image=sscanf('filename','%s') ;
ext=sscanf('.png','%s') ;
%%do your stuff
filename=strcat(name_image,num2str(jj),ext);
print(h_f,'-dpng','-r600',filename)
end
If you want to execute your script multiple time (because you don't want to use a "for") just declare a variable (for example jjthat will be incremented at the end of the script:
jj=jj+1;
Be careful to don't delete this variable and, when you start again your script, you will use the next value of jj to compose the name of the new image.
This is just an idea

Exporting all values from workspace to excel or csv

Is there some way to export all variables from workspace on to an excel spreadsheet or a csv file, automatically. I have 100 + variables, and I do not want to iteratively export one variable at a time, referring each variable by name if possible.
You can write each variable to a different sheet in the spreadsheet:
S = whos; %// get all variables
xslfilename = 'savedFile.xslx';
for ii = 1:numel(S)
cmd = sprintf( 'xslwrite( xslfilename, %s, ''%s'' );', S(ii).name, S(ii).name );
eval( cmd ); %// not very happy with using `eval`...
end
Use whos to list all variables currently in workspace, and xlswrite to write each variable to a different sheet of the same xls file.
When reading the file you can use xlsinfo to get all sheets names
[status,sheets] = xlsfinfo( xslfilename ); %// get all sheet names = variable names
Now you can read each variable from each sheet using xslread.
This might not be what you're looking for, but if you're trying to save the workspace in order to load it back to MATLAB later, use the save and load functions.

save svm models to file matlab

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.

Appending data to a mat file in MATLAB

I have a mat file with some data and i want to add additional data at the end of file whenever a function is called. How can i do it? By save -append my existing data is overwritten. But for me data should not be overwritten. Reply as early as possible.
You've given no information about the type of data you are storing, but I suspect you might be trying to append values to an array which is stored in a file using -append; however, -append only adds new variables to a file. If you save a variable with the same name, it will overwrite it. Instead, just do the append manually:
I'll assume that we are talking about a 1xn vector, you can adjust the concatenation step as necessary.
x = load('myfile');
x = [ x newX ];
save('myfile', 'x');