Save or Load Data from/to GUIDE/Workspace - matlab

I'm new in GUIDE in MATLAB. I have two different problems:
I would like to save in a .mat file all variables (about 1000) from workspace using a button in GUI in MATLAB. How can I do?
I have a button where after press on it I'm able to load a specific .mat file from my path, always using GUI, but I would like that the variables contained in this file, became presents in the base workspace.
In other words, I have a button, "LOAD", in GUIDE in MATLAB where I can load a .mat file, and the variables contained in the .mat file must be loaded into the 'base' workspace when the button is clicked.
Please help me.

For your first question, I would suggest just putting a command like save('filename.mat'); in the "Save" button's callback. But what variables? If they are in the base workspace, see my answer to your second question below.
To load data into the base workspace, you might try the evalin command:
evalin('base','load(''filename.mat'')');
The 'base' argument tells it to run the command in the base workspace.
If your file name is in a variable:
fname = 'filename.mat';
evalin('base',['load(''' fname ''')']);
Alternatively, you could use sprintf:
loadCmd = sprintf('load(''%s'')',fname);
evalin('base',loadCmd);

Related

Uploading multiple .txt files at once on MATLAB GUI

I would like some guidance on how to import multiple .txt files containing data seperated by comma on a MATLAB GUI. Once the files are uploaded, I have a function that will manipulate all the data from each .txt file.
Any help is appreciated.
The easiest way to import multiple files is to:
Use the file importer GUI in matlab and generate a script after you
selected your preferred parameters
Generate a script (there is a button to generate a script in the importer)
Modify the script with a for loop to load multiple files and save them in a variable (a cell array can handle different sizes of data in each file)
Try uigetfile to launch a dialog for loading files. Set 'MultiSelect' to 'on' in order to select multiple files at once.
Here's an example call:
[filenames, pathname] = uigetfile({'*.txt; *.csv','Comma separated values';...
'*.*','All files'},'Select files','MultiSelect','on');
You will need to check if the user actually selected a file or if they canceled.
If I understand your question correctly, you have a GUI already. In this case you just need to add the above call to your designated callback function (i.e. whatever you click to invoke this file load interface).

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 the matlab workplace variable including original file name?

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.

saving data from workspace to different dirrectory in matlab

I have a loop which my main script run through that. I wounder to save some of my variables in different directory every time that my loop is running. I have used following script but its not working:
for i=1:size(whisk, 1);
my codes is here and it creates variables in my workspace like [format, measurements].
the rest is what I wote to save this variables:
mkdir('C:\videos\results\', num2str(i));
dumvar=0; % As matlab has problem with data>2GB, then I use this 2 line code for saving
save('measurenments','dumvar','-v7.3');
save(fullfile('C:\videos\results\', num2str(i),'measurenments'));
clear all;
close all;
end
but Unfortunately its not work!!!!!!!!!!!
Any help would be appreciated.
Sam
Except that measurenments is wrongly spelled (correct spelling is measurements), there is not so strange that it does not work. The first call to save, saves the variable dumvar in the current folder, with the format v7.3. The second call to save, saves the whole workspace as a file fullfile('C:\videos\results\', num2str(i),'measurenments'). Try this,
save(fullfile('C:\videos\results\', num2str(i),'measurenments'),'dumvar','-v7.3');
However it seems as the folder fullfile('C:\videos\results\', num2str(i),'measurenments') does not exist since you only create the folder mkdir('C:\videos\results\', num2str(i))
. Then matlab cannot save anything there. Try either to save as fullfile('C:\videos\results\', [num2str(i),'measurenments']) or create the directory mkdir('C:\videos\results\', [num2str(i),'\','measurenments']);
`

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