MATLAB: How to save variables to a specific cell in a .mat file

filematsave

I have a .mat file, called Threshold_values.mat, which consists of an array (68×1) and just contains cluster1, cluster2, cluster3 etc. in each cell.
I use a GUI to look at each cluster individually and calculate 6 different variables.
I need to write these 6 variables alongside the cluster name in different columns. How can I save these into the .mat file and keep them there?
I am already using strcmp to know which row I need to write to in the file.

Best Answer

By far the easiest solution, generally speaking, is to just load the whole matrix in from the mat file and then you just write to the indices you have worked out, then save the whole thing back again to file.
Don't try to update live to file unless you have a good reason to do so. If you had a vast data set then this might be the case and a matfile approach (note that 'matfile' is distinct from a normal mat file, but you don't need to bother about the distinction for your size of data set) would likely be sensible, but 68x7 is a very small data set that has no problem being loaded into memory.
I think since you are new to Matlab you are mixing up some terminology, so just a few points for clarification (hopefully):
  • A .mat file is simply a Matlab file type into which you can basically save a whole workspace - i.e. any number of different variables of whatever type you wish - it is not limited to being a single entity and so isn't like if you were trying to write your data into a binary or text file.
  • A 'cell' in Matlab is generally used to refer to an element of a cell array which is a special type of array in which you can store a large variety of different data types. As an ideal to aim for you should only use cell arrays when you really need to. For raw data use a standard array - its manipulation is far easier because its whole purpose is to store numeric data to do operations on.
  • When you talk about 'titles' of columns I'm not 100% sure what structure you have, but if you have a cell array for your entire data purely because you want one row of titles followed by 68 rows of pure numeric data then don't do this!! There is a 'table' structure in Matlab which you can learn about, but for something this simple you can also simply store your column titles in a separate variable as e.g.
columnTitles = { 'Clustername', 'minPV', 'maxPV', 'ThreshPV', 'minArea', 'maxArea', 'ThreshArea' };
then your data can be stored in a standard numeric array e.g.
data = zeros( 68, 7 );
You can then search the column titles array for your indices (probably in the same way you do now) and use these for the columns of the numeric matrix.
This is essentially like a table except that you have to manually ensure that your array of titles is the same length as you have columns of data so there is a little more manual overhead than using
doc table
On the other hand it is simpler for a beginner I would think.