.mat file variable is overridden with save - matlab

I have a matlab file which contains these values :
Opening the file, here a snippet of X :
And y :
Deleting all rows in y and saving, need to replace the current file :
Replacing the file causes all of the X values to be removed also :
Can see from above the variable 'y' is no longer present.
How can edit a .mat file 'y' variable without removing the 'X' variable ?

Use the '-append' option when saving.
Doing save('data.mat','x','-append') or save data.mat x -append will either append the data or substitute the variable without modifying the rest of the data.

If you have Matlab R2011b of later, you can also use the matfile function to get a dynamic handle to the data stored in the MAT-file. This is typically reserved for large files with data that should only to be loaded into memory when needed, but the functionality is similar to using save and more interactive. For your current example:
x = rand(5000,400);
y = rand(5000,1);
save('data.mat','x','y');
m = matfile('data.mat','Writable',true);
m.y = [];
And y in the MAT-file is automatically updated.

Related

Matlab saving a .mat file with a variable name

I am creating a matlab application that is analyzing data on a daily basis.
The data is read in from an csv file using xlsread()
[num, weather, raw]=xlsread('weather.xlsx');
% weather.xlsx is a spreadsheet that holds a list of other files (csv) i
% want to process
for i = 1:length(weather)
fn = [char(weather(i)) '.csv'];
% now read in the weather file, get data from the local weather files
fnOpen = xlsread(fn);
% now process the file to save out the .mat file with the location name
% for example, one file is dallasTX, so I would like that file to be
% saved as dallasTx.mat
% the next is denverCO, and so denverCO.mat, and so on.
% but if I try...
fnSave=[char(weather(i)) '.mat'] ;
save(fnSave, fnOpen) % this doesn't work
% I will be doing quite a bit of processing of the data in another
% application that will open each individual .mat file
end
++++++++++++++
Sorry about not providing the full information.
The error I get when I do the above is:
Error using save
Argument must contain a string.
And Xiangru and Wolfie, the save(fnSave, 'fnOpen') works as you suggested it would. Now I have a dallasTX.mat file, and the variable name inside is fnOpen. I can work with this now.
Thanks for the quick response.
It would be helpful if you provide the error message when it doesn't work.
For this case, I think the problem is the syntax for save. You will need to do:
save(fnSave, 'fnOpen'); % note the quotes
Also, you may use weather{i} instead of char(weather(i)).
From the documentation, when using the command
save(filename, variables)
variables should be as described:
Names of variables to save, specified as one or more character vectors or strings. When using the command form of save, you do not need to enclose the input in single or double quotes. variables can be in one of the following forms.
This means you should use
save(fnSave, 'fnOpen');
Since you want to also use a file name stored in a variable, command syntax isn't ideal as you'd have to use eval. In this case the alternative option would be
eval(['save ', fnSave, ' fnOpen']);
If you had a fixed file name (for future reference), this would be simpler
save C:/User/Docs/MyFile.mat fnOpen

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.

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.

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

Saving a file in MATLAB with a variable filename in a loop [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Save mat file from MATLAB
How to tell MATLAB to open and save specific files in the same directory
I have a set of CSV files and need to extract data to obtain plots. I use the following code to generate a variable file name in a loop and accordingly get the desired data.
P = dir('*.csv');
for m = 1:length(P)
P(m).data = csvread(P(m).name);
end
I now want to modify these CSV files (change the data values in the CSV files) before obtaining the desired data and then save these files to Excel format (.xls) within the loop.
Something like
for i = 1:length(P(m).data)
if P(m).data(i,1)< value1
P(m).data(i,2) = 0;
end
save P(m).xls P(m).data -ascii; % Gives error "save 'P(m).data' is not a valid variable name."
end
How do I save a file in Excel (.xls) format with a variable filename obtaining data from array in a loop?
Check out the MATLAB documentation for the save() function
You need to use the function-call syntax to use variable file names:
save(P(m).xls, P(m).data, '-ascii');
Edit: you seem to have new errors. I can see two things:
your P variable is a struct array, so it has more than 1 element -- save() can save only one file at a time;
2 xls is not a file of your struct, which has a name field.
To save your data, it will probably resemble this:
for m = 1 : length(P),
save(P(m).name, P(m).data, '-ascii');
end
If you want to replace the extension to avoid overwriting your files (I assume xls is what you wanted), this should do the trick:
for m = 1 : length(P),
name = P(m).name;
name = name(1:find(name,'.'));
name = [name '.xls'];
save(name, P(m).data, '-ascii');
end