I run my scripts which produce hundreds or thousands of .mat files. Each of this file contains two variables: resultsU and resultsT. I want to append the files but not overwrite the variables. What is the easiest way to do so in Matlab? Some suggest manual manipulation of the .mat file which is not easy or efficient to do when you have hundreds of .mat files.
How to append multiple .mat files that have the same variable names in them?
1.8k Views Asked by JustCurious At
2
There are 2 best solutions below
9
rayryeng
On
It's actually a lot easier than you think. If you want to append to MAT files, simply use save with the -append flag. Assuming that you have a few variables... let's call them p and q, and assuming you have a file called test.mat, it's very simply:
save('test.mat','p','q','-append');
The beauty of this is that you don't need to load any of the variables in the MAT file and resave them with the appended variables. This appends the desired variables into the MAT file without you ever having to load them into MATLAB.
If you have a bunch of .mat files in a directory, you can do something like this:
folder = '...'; %// Place directory here
f = dir(folder); %// Find files
%// For each file...
for idx = 1 : numel(f)
name = fullfile(folder, f(idx).name); %// Get path to file
%// Do some processing
%//...
%//
%// Append to file
save(name, ..., ..., ..., ..., '-append');
end
What goes inside the ... for save are the variables you want to append to each file.
Related Questions in MATLAB
- Convert Cell Array of Symbolic Functions to Double Array of Symbolic Functions MATLAB
- How to restrict vpasolve() to only integer solutions (MATLAB)
- "Error in port widths or dimensions" while producting 27
- matlab has encountered an internal problem needs to close
- Minimize the sum of squared errors between the experimental and predicted data in order to estimate two optimum parameters by using matlab
- Solve equation with Crank Nicolson and Newton iterative method in Matlab
- Why options are not available in EEGLAB menu options?
- ash: ./MathWorksProductInstaller: not found, but file exists
- iterative GA optimization algorithm
- Create Symbolic Function from Double Vector MATLAB
- Fixing FEA Model loading with correct units and stress results
- loading variables from a python script in matlab
- Why cannot I set font of `xlabel` in `plotmf` in MATLAB?
- How would I go about filtering non-standardly formatted serial data which contains some junk binary between data entries?
- Cyclic Voltammetry Simmulation in MATLAB, I am running into issues with my data points returning as NaN values, i am a beginner, any help wanted
Related Questions in VARIABLES
- .bat file - How can I return the value of a variable whose name depends on another variable concatenated with a string in a batch file?
- Accessing Secret Variables in Classic Pipelines through Java app in Azure DevOps
- Does tensorflow have a way of calculating input importance for simple neural networks
- Can you define a variable in ranges in java
- How to only estimate neonatal mortality using syncmrates in Stata?
- PHP string variable to multiple rows in table sql insert
- Good practices for variables in Laravel's layout files
- Variable in Python going up by more than 1 at a time
- Accessing a variable from a string
- Encapsulation does not seem to work in dart
- TypeError: indice_delete() takes 0 positional arguments but 3 were given
- Altova Mapforce - How to use results from Tokenize at the same time in a database call?
- Powershell v5 - variable name replacement when referring to WPF objects
- Use javascript variable in document.querySelector (howTo)
- usage of multinomial assign javascript?
Related Questions in SAVE
- Flutter: How to add items and save it in local storage?
- Can be their an extension to save pages in as offline in the browser itself?
- Excel VBA macro works flawlessly on my computer, but has different errors on different machines?
- Cannot save a Custom Variational Autoencoder Model built in Keras with tensor flow
- String Type Value Member and Display Member in VB.NET Combobox with manually filled data
- VBA Word changing command button properties prevents closing without save prompt
- How to save plots one at a time from momentuHMM fit object?
- what is the expected behavior if you try to save an openpyxl workbook on a file that is already open?
- Nextjs: How to save simple data even in a way that are not lost when navigation between routes?
- Excel VBA unable to save file on a network drive
- Android Studio Error : Class declares multiple JSON fields named 'mLifecycleRegistry';
- How to save a file in Files iOS system app in iOS 17 Swift
- Saving a base64 code into a folder gives me a failed image and cannot open it with PHP
- In Oracle Cloud Infrastructure, how to upload a csv file generated in a notebook directly into a bucket?
- Tensorflow - Save & Load custom model in Keras v3 format
Related Questions in LOAD
- How to configure api http request with load testing
- Laravel 11 Staudenmeir BelongsToThrough Undefined Relationship
- Context Deadline exceeded and WebSocket Url timeout issue
- WebIX Loading Icon Spin until method is completed
- Performance of loading Time and influxdb
- Load Testing, Performance Testing , Jmeter
- Feature Request: Enumeration of issues with Workspace Trust "Do you trust the authors of the file in this folder?"
- How to abort a fetch request when it is made using load method of loaders.gl
- Authorisation code Flow with PKCE using Jmeter
- When will SQLite through SQLITE_IOERR_SHMMAP error? SQLite C library
- Error invoking remote method 'DB_CONNECT': Error: Host 'x.x.x.x' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'
- Call a function on every resize and load
- GCP Failed load job, how to get the source json
- Dropdown Not Populating with Dynamic Data in React Component
- How to fix Android studio Unable to load class 'org.gradle.initialization.BuildCancellationToken' error
Related Questions in MAT
- Angular mat-form-field asks for "must contain a MatFormFieldControl", but it is a display-only text box
- How to prevent dropdown closing on selecting date from mat datepicker
- Can't start MemoryAnalyzer-1.15.0.20231206-win32.win32.x86_64
- How to load Dymola simulation results into Python?
- java.lang.ref.Finalizer piled up
- Apache flink metaspace exception while running job several times
- Convert matlab data in mat file containing many arrays into numpy arrays
- Error when trying to mutate a dataframe containing lists
- Why are the results different when multiplying OpenCV Mats?
- What the real Time complexity of Fibonacci recursion function
- Emgu.CV Mat vs Image<,> pixel access Get Set
- How to get actual value from the .mat ref file
- The difference of " *mat.ptr<float>(i,j)" and "*mat.ptr(i,j)"?
- Transfer nested array to csv file
- TIFF file read as cv::Mat imported to vtkImageData makes program crash (Qt C++)
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
rayryeng's answer is good if running the code which created the files is an option. However, if working with a huge amount of files is a given fact which you need to deal with, I would suggest to go about this using and array of
structs(which resemblesstructconcatenation).Consider the following example function:
What it does is to combine
.matfiles containing the same variable names. Now you can runcombined_results = CombineMat(folder_with_mat_files)and get astructwhich contains all the different results (assuming you have enough memory to hold them). After you have thisstructin memory, you can save it to a single.matfile.Note 1: If you don't have enough memory to load all the files, you can add another piece of code to
CombineMatthat dumpscombined_resultsto disk and clears it after a certain amount of loop iterations (possibly with the'-append'option as suggested by rayryeng. This personally doesn't make sense to me if OOM happens, because then you would have problems loading the resulting file :)Note 2: Obviously, if you want your result as something other than an array of
structs, the code needs to be modified accordingly.In a more general case, where you are trying to concatenate structures with different variable names, you can use the following FEX submission (which I can recommend from personal experience!).
P.S. My code was written on MATLAB 2015a.