Appending data to a mat file in MATLAB - 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');

Related

How do you call a function that takes in a MAT file, manipulate the data in that file, and create a new textfile with that same MAT file name?

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.

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

.mat file variable is overridden with save

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.

How to use append command in 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');

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.