How to save the matlab workplace variable including original file name? - matlab

I would like to know how I can save the matlab output files (i.e. matlab workplace variables), by including original file name.
e.g. I open a file (filename.mat) with load filename.mat. Then I run a code to do calculation and I get some workplace variables (e.g. flow, pressure). I want to save those variables as filename_flow.mat and filename_pressure.mat.
I will use the same code on different filename, so I would like to know how I can save my variables as mentioned above (i.e. including the original file's name)?

FileToBeLoaded = 'filename.mat';
[pathstr,filename,ext] = fileparts(FileToBeLoaded)
load([filename ext]);
%// calculate stuff
FlowVariable = %// some calculation
save([filename '_flow'],FlowVariable)
The same of course works for other names as well. You pull apart the original file name to its actual name and extension, and use the original name, add something (_flow in this case) and save that. The default of MATLAB is already to save to a .mat file, so that's taken care of automatically.

Related

How do I prompt the user to choose a file that will be loaded in matlab?

I want the user of a script I'm writing to be able to navigate to a file containing their data and to load the data into the workspace. For example, if a csv file contains two cells with the values 1 and 2 respectively, I want the user to simply choose this file and those two values will be assigned to a variable in the workspace.
I have looked at using:
filename = uigetfile('*.xlsx','*.csv')
But that just returns the name of the file. Perhaps I could construct a full path to where the file they choose is found, and then read it in that way (using xlsread or csvread) but I think I'm probably missing something here. It seems that there should be a more straightforward way of doing it.
I believe that you're looking for the uiopen() function. This function will:
Open dialog box for selecting files to load into workspace.
On default, this function will display in a file explorer dialog box with the filter set to all MATLABĀ® files (with file extensions *.m, *.mlx, *.mat, *.fig, *.mdl, and *.slx).
However, you can import data from data files like CSV files and spreadsheets as well. Simply select the (All Files) option for the Files of Type field.
Once you've selected the data file you're interested in, you will be prompted with another GUI object that previews the data you are about to load into MATLAB's workspace. If you're satisfied with the format of the variables presented in the preview, simply hit the green check-mark at the right-side of the tool-box ribbon in the GUI object and, huzzah, all of the data file's contents have been loaded into separate variables (named according to their respective headers).
Alternatively, though this is undeniably a longer-winded and uglier approach, if you'd like to use the filename returned from uigetfile('*.xlsx', '*.csv'), you could use the importdata() function. This will output a struct that contains each of the variables from your data file as a separate field:
[filename, pathname] = uigetfile( ...
{'*.csv;', 'CSV file (*.csv)';
'*.xlsx', 'Excel Spreadsheet file (*.xlsx)'; ...
'*.*', 'All Files (*.*)'}, 'Pick a File to Import');
full_filename = fullfile(pathname, filename);
[A, delimiterOut] = importdata(full_filename);

How to save a mat file in another directory in matlab

I want to save a matrix (e.g. "PTX_Data_Raw.mat") in another folder (e.g. Temp folder). I have written below code:
mkdir('D:\Projects\ProgrammingPart\Method2_FinalApproved\8-congruent','Temp');
filename=('D:\Projects\ProgrammingPart\Method2_FinalApproved\8-congruent\Temp');
save(filename,'PTX_Data_Raw.mat');
but it didn't work. Does anybody can help me for solving this problem?
THX
Going with your comments, you are using save wrong. The first parameter is the filename you want to call the MAT file and second parameter and onwards are the variables you want to save.
Therefore, you need to make sure filename contains the entire filename, including the path followed by the actual name of the MAT file you want. After, the second parameter is PTX_Data - the name of the matrix you want to save.
mkdir('D:\Projects\ProgrammingPart\Method2_FinalApproved\8-congruent','Temp');
%// Change
filename=('D:\Projects\ProgrammingPart\Method2_FinalApproved\8-congruent\Temp\PTX_Data_Raw.mat');
save(filename,'PTX_Data'); %// Change

Get filename from Edit text in Matlab?

I want to write the file name in the gui edit text and save edit text as my filename. Than I could be able to save filename as I wish. For instance; My file is an Neural network file which could be save as *.mat file; here is my code
%network_name is my edit text
name = get(handles.network_name,'string');
name = net;
save name
But it doesn't work I can't manage file name from edit text :(
It saves as name that l wrote next to save (name.mat). Thanks for your any answer...
Why name = net;?
That aside, if you want to pass the filename as a variable to the save function, you need to use this syntax instead:
save(name)
save name is the "command form", and save('name') is the corresponding "function form". As you can see you can only give string inputs when using command form, whilst you actually want to pass a variable.
To conclude: if you are passing variables to a function, use function form.
If you want to save particular variables, use:
save(name,'net');
Note that name (which we want to be the string contained in the variable) isn't in quotes and net (the name of the variable we want to save) is.
A warning about this is actually buried in the documentation for save.
Do not use command form when any of the inputs, such as filename,
are variables.
save name
will save all of the variables in your workspace to a *.mat file called 'name'
Also your code is basically overwriting itself, line 2 sets the variable name to be a string, but then line 3 writes some data net to that variable.
I'm a little confused as to exactly what you want but I think you want to save the variable net to a mat file with the name that you read in the string from get(handles.network_name,'string')
If that is what you want to do then its just
save(get(handles.network_name,'string'), net)
If you want to save all the open variabile in the workspace then its just
save(get(handles.network_name,'string'))

Save workspace of unknown workspace in Matlab

Is it possible to save workspace variables from a function that I am calling and cannot explicitly edit without file I/O?
I know I can use the save function to save all of the variable names in a workspace, but what if I wanted to save the workspace variables from a function that I am calling, like a built in function (mean, sum, etc).
I would like to save all of the variables from a function's workspace before it returns back to the function I am writing, and I would like to do it without opening the file each time and adding an extra line of code; is this possible?
In case anyone is interested:
I have yet to find a solution to the exact question I asked, but I found a solution that works well enough with a little extra file tracking.
Using the function onCleanup, you can specify that all the variables be saved right before the function returns to the caller. Using this and a little file parsing, you can open the code in question as a simple text file, and insert the onCleanup code anywhere in the file (easier than inserting save as the last line). Then, you can run the code and track the new .mat file using the previous file name or any naming method you choose.
That will enable you to save all the variables in a workspace just before the function exits, but it does require file parsing, see simple example below:
readFile = fopen('filename.m');
writeFile = fopen(['filename_new.m']);
%Ignore the first line (hopefully the function header, may need extra parsing if not)
functionHeader = fgets(readFile);
%Print the function header
fprintf(writeFile,functionHeader);
%Print the clean-up code
%NOTE: This can go anywhere in the file
fprintf(writeFile,sprintf('onCleanup(#()save(''%s.mat''))\n',filename)));
nextLine = fgets(readFile);
while ischar(nextLine)
fprintf(writeFile,nextLine);
nextLine = fgets(readFile);
end
With the above, a new file is created (filename_new.m) which needs to be run, and will create a mat file (filename.mat) with all of the workspace variables in it.
eval(newFileName(1:end-2));
Now, by tracking the .mat file, you can do whatever is necessary after this point. For my purposes, I was interested in the memory used by the said function, which is available by accessing the mat object of the .mat file.
matObj = matfile('filename.mat');
stats = whos(matObj);
fileSize = sum([stats.bytes]);
Try the "save" function.
Add this line in your called function:
save('filename')
Here is my sample code:
a=10; b=6;
c=addition(a,b);
And the function is defined as:
function [out]=addition(a,b)
out=a+b;
temp1=a;
temp2=b;
temp3=a-b;
save('C:\data.mat');
end

Load multiple .mat files for processing

In MatLab I have (after extensive code running) multiple .mat files outputted to .mat files. The actual matlab name of each .mat file is called results but I've used the save command to write them to different files. A small subset of the files looks like this:
results_test1_1.mat
results_test1_2.mat
results_test1_3.mat
results_test1_4.mat
results_test2_1.mat
results_test2_2.mat
results_test2_3.mat
results_test2_4.mat
Now I want to compare the results for each test, which means I have to load in all four .mat files and combine them in a graph. Reading in one file and making the eventual graph is no problem. But since all files have the same matlab name results, iteratively loading them is not an option (at least, not one that I know of yet) since in the end only file 4 remains since it rewrites the previous ones.
Is there a way to load all these files and store them in different variables in a structure (regarding only one test set)? Because doing all this manually is a hell of a lot of work.
I've tried to use this method: Load Multiple .mat Files to Matlab workspace but I get an Invalid field name error on loaded.(char(file)) = load(file);
You can load into a variable (preferably a cell array)
results = cell( 2, 4 ); % allocate
for testi=1:2
for resi = 1:4
filename = sprintf('results_test%d_%d.mat', testi, resi );
results{testi,resi} = load( filename );
end
end
Now you have all the results stored in results cell array and you may access the stored variables, e.g.,
results{1,3}.someVar % access variable someVar (assuming such variable was saves to the corresponding mat file