How does one load a .mat file in the GUI, matlab app development - matlab

I am attempting to create a MATLAB app that saves the specific fields in a .mat file and allows for custom naming. Saving has seemed to work however attempting to load leads to nothing changing.
Any help would be appreciated
function SaveButtonPushed(app, event) % Saving element
props = properties(app);
lp = length(props);
values = cell(1,lp);
visibilities = cell(1,lp);
for i = 1:lp
propName = props{1};
property = app.(propName);
if isprop(property, 'Value')
values{i} = app.(propName).Value;
end
% if isprop(property, 'Visible')
% visibilities{i} = app.(props{i}).Visible;
% end
end
file = uiputfile('*.mat', "Save Message" );
if file
save(file, 'props', 'values', 'visibilities');
end
end
function LoadButtonPushed(app, event) % Loading element
[file,path] = uigetfile('*.mat');
selectedfile = fullfile(file);
load(selectedfile)
end

It is like Wolfie said in his comment. The variables in the .mat file are loaded into the private workspace for that function, which is cleared at once it exits.
So within the function you should be able to loop over your app properties again and set the values the ones loaded from the file.
Note that if you add a breakpoint, as Wolfie says, you should be able to see the private workspace and your loaded variables will be there until the function exits.
Alternatively, you could load the variables in to a structure:
S = load(selectedfile);
(See https://uk.mathworks.com/help/matlab/ref/load.html for more details)
and return that structure,
function [S] = LoadButtonPushed(app, event) % Loading element
You will have to change the interface/load function call to accept the returned variable, and I'm not sure that you can add the contents of the structure to the global namespace. However, you can access them through the loaded structure as:
S.props

Related

why my structure variable does not contain the changes applied by my handle functions

I created a structure that contains fields and a group of handles functions.
I initialized my structure when I press a button from my Matlab GUI, and then I proceed to call my handle functions, which either add new fields to my struct or update the default ones.
However, I have difficulty to see the changes, despite assigning the structure to my workspace, as I wish to call it in other functions to use the updated fields.
I used assignin(ws,var,val) and evalin(ws, expression)
function struct = initialisedStruct(arg)
struct = struct ();
struct.a = arg;
struct.b = 1;
struct.run= {...
#aaaa,... %update some existed fields
#bbbb, ...%add here a new field call c. -> struct.c now exists.
#cccc,... %do something else
};
end
function [applyToStructure] = applyMethod(applyToStructure, handles)
for i = 1:length(handles)
[applyToStructure] = handles{i}(applyToStructure);
end
end
function clickOnThisButton(hObject, eventdata, handles)
input = 12;
struct = initialisedStruct(input);
applyMethodHandles(struct, struct.run); %modify the struct
assignin('base', 'struct', struct);
end
function clickOnAnotherButton(hObject, eventdata, handles)
myvar = struct.c; % here is my problem as it does not exist
end
I was expected after applying applyMethodHandles which loops through each handle containing in the run field and using assignin, to see in the workspace my struct variable with its new fields.
You are not grabbing the output of the function. There are no references in matlab, you need to copy the new modified structure.
Instead of:
applyMethodHandles(struct, struct.run); %modify the struct
Do:
struct=applyMethodHandles(struct, struct.run); %modify the struct
Also struct is the worst name you can choose. Not only is bad programming because it says nothing about what it is, you are shadowing MATLABs struct name, so it can not use it. I strongly suggest changing the name.

How to identify the script that produced a specific workspace variable?

I am learning about an existing code, which produces lots of different variables. My goal is to identify the variable in the workspace and localize the script that produced this variable.
I need to localize the script, because in the code I have a script that calls the other three scripts. For this reason it is difficult to identify the script that produced a specific variable. Besides, the three codes are very long.
How can I identify the source script based just on the workspace variables?
I recently had a similar problem, so I hacked a quick function together, which will detect newly created variables, based on an initial state.
function names2 = findNewVariables(state)
persistent names1
if state == 1
% store variables currently in caller workspace
names1 = evalin('caller', 'who');
names2 = [];
elseif state == 2
% which variables are in the caller workspace in the second call
names2 = evalin('caller', 'who');
% find which variables are new, and filter previously stored
ids = ismember(names2,names1) ~= 1;
names2(~ids) = [];
names2(strcmp(names2, 'names1')) = [];
names2(strcmp(names2, 'names2')) = [];
names2(strcmp(names2, 'ans')) = [];
end
To use this, first initialize the function with argument 1 to get the variables currently in the workspace: findNewVariables(1). Then run some code, script, whatever, which will create some variables in the workspace. Then call the function again, and store its output as follows: new_vars = findNewVariables(2). new_vars is a cell array that contains the names of the newly created variables.
Example:
% make sure the workspace is empty at the start
clear
a = 1;
% initialize the function
findNewVariables(1);
test % script that creates b, c, d;
% store newly created variable names
new_vars = findNewVariables(2);
Which will result in:
>> new_vars
new_vars =
3×1 cell array
{'b'}
{'c'}
{'d'}
Note, this will only detect newly created variables (hence a clear is required at the start of the script), and not updated/overwritten variables.
You could use exist for this. Roughly:
assert( ~exist('varName', 'var'), 'Variable exists!');
script1(in1, in2);
assert( ~exist('varName', 'var'), 'Variable exists!');
script2(in1, in2);
assert( ~exist('varname', 'var'), 'Variable exists!');
When the assertion fails, it means that the variable was created.

How can I access data from outside the app class in appdesigner (Matlab)

I have created a very simple GUI in appdesigner (Matlab) with one dropdown menu. Additionally, I took the code that got generated (under 'Code View' tab) and pasted that in a normal .m file (because, I want to further add some more contents to this code). My question is how can I access certain variable from this self generated code, so that I can play with that value outside of the main class?
For example:
In App class, for this dropdown menu section, following line of code got generated:
app.ColorDropDown = uidropdown(app.UIFigure);
app.ColorDropDown.Items = {'Red', 'Blue', 'Yellow'};
app.ColorDropDown.Position = [277 178 140 22];
app.ColorDropDown.Value = 'Red';
Outside of this app class: Depending upon the value that was selected in this dropdown menu, I want to capture that in a normal variable, and show some other results based on the color selected
Thanks
It seems like the essence of your question is about sharing data between GUIs as you state you want to "show some other results based on the color selected".
Note: MATLAB documentation cautions: Do not use UserData property in apps you create with App Designer.
The documentation goes on to recommend approaches for sharing data among app designer apps and creating multiwindow apps in app designer.
For the sake of completeness, I'll provide a detailed example, different from the MATLAB documentation, of how this can be accomplished entirely within the App Designer.
Setup
I created 2 app designer apps, controlGUI.mlapp and plotGUI.mlapp. Running controlGUI() loads both mlapp files at once and then allows you to control aspects of the plotGUI from callbacks in the controlGUI. Of course, the plotGUI could do anything but I have it changing visual aspects of the plotted data.
Details
For simplicity, I am setting the controlGUI be the main application. I can do this be adding a property in controlGUI named PlotWindow and having it contain the output of calling plotGUI(); the other mlapp. I also have a callback function I recycle for the three dropdowns that updates a DATA property in the plotGUI. This DATA property has a listener attached that fires a callback to update the uiaxes object.
The plotGUI
The magic is really in this object. That is, I created a property named DATA and altered the access. By setting the property access SetObservable = true, we can then add a PostSet event listener, which I stored in a private property called dataChangedListener during the startupFcn.
properties (Access = public, SetObservable=true)
DATA % A struct with xdata, ydata, fields. Other line prop fields ok
end
properties (Access = private)
dataChangedListener % listener object for when DATA is changed.
end
Then the startup function, startupFcn, initializes the DATA property with some (arbitrary) data as struct then adds and enables the PostSet listener.
% Code that executes after component creation
function startupFcn(app, data)
if nargin < 2
% create a default dataset
data = struct();
data.xdata = linspace(0,1,1001);
data.ydata = sin(data.xdata.*2*pi*10);%10hz signal
data.color = app.Axes.ColorOrder(1,:);
end
app.DATA = data;
% plot the data
line(data, 'parent', app.Axes);
% add and enable PostSet event listener for the DATA property
app.dataChangedListener = addlistener(...
app,'DATA','PostSet', ...
#(s,e) app.updatePlot ...
);
app.dataChangedListener.Enabled = true;
end
The PostSet listener calls the method app.updatePlot(), so we have to add this method to our app. This method will get called whenever anything in app.DATA gets modified. So I created the "function" (as the Code Browser calls it) which simply deletes the axes children (the existing line) and uses the low-level version of line() to draw a primitive line based on the app.DATA struct object:
function updatePlot(app)
%clear plot
delete(app.Axes.Children);
% draw the new plot
line(app.DATA, 'parent', app.Axes);
end
Yes, line() will accept a struct which has field names that correspond to valid line properties but I can't seem to find the reference specifically. But if you read about the inputParser object... sorry, getting off topic.
The controlGUI
This object is simpler. It holds the plotGUI in a property, allowing direct access to the plotGUI properties and public methods.
properties (Access = public)
PlotWindow = plotGUI() % holds the reference to the plot window
end
I also created an updatePlot callback method here, different from the plotGUI method, bad naming on my part. Nonetheless, this control method takes the values from controlGUI dropdowns and then modifies the plotGUI DATA struct, stored in app.PlotWindow.DATA. So this one callback is called whenever any of the dropdowns are changed (ValueChangedFcn). Consequently, the PostSet listener for the DATA struct will fire the callback to update the plot accordingly.
% Value changed function: LineColor, LineStyle, MarkerStyle
function updatePlot(app, event)
mStyle= app.MarkerStyle.Value;
lStyle= app.LineStyle.Value;
lColor = app.LineColor.Value;
d = app.PlotWindow.DATA;
switch mStyle
case 'none'
d.marker = 'none';
case 'circle'
d.marker = 'o';
case 'diamond'
d.marker = 'diamond';
case 'point'
d.marker = '.';
end
switch lStyle
case 'none'
d.linestyle = 'none';
case 'solid'
d.linestyle = '-';
case 'dashed'
d.linestyle = '--';
case 'dotted'
d.linestyle = ':';
end
d.color = lColor;
% set the data back into the plotGUI
% The plotGUI's DATA PostSet listener will update the actual plot
app.PlotWindow.DATA = d;
end
You aren't supposed to copy/paste the code outside of the code editor with App Designer. If you want to add your own code, you should add a new function to your class using the "Function" button in App Designer. The app can also call any other matlab function so you could just pass the information from the app to another function by calling it inside the App Designer code
For example see this example from a demo I created. It uses a drop down ChartTypeDropDown to determine what type of chart it should draw. I added a new function called DrawChart which uses the data from the GUI to draw a graph depending on the values selected/entered in to the various boxes.
function results = DrawChart(app)
chartType = app.ChartTypeDropDown.Value;
chartTime = app.TimeEditField.Value;
chartA = app.AEditField.Value;
chartB = app.BEditField.Value;
chartC = app.CEditField.Value;
t = [0:0.1:chartTime];
if strcmp(chartType,'Sin')
y = chartA * sin(chartB*t)+chartC;
elseif strcmp(chartType,'Cos')
y = chartA * cos(chartB*t)+chartC;
elseif strcmp(chartType,'Exp')
y = exp(t);
else
y = x;
end
ax = app.UIAxes;
ax.Title.String = chartType;
plot(ax,t,y);
end
This function is called by the callback linked to a button
function DrawButtonPushed(app, event)
DrawChart(app);
end
Note how I call regular matlab functions such as sin/cos/exp. These could just as easily be a Matlab function that you have written.

Will returned array be copied by value or returned as reference in MATLAB?

I wanted to ask how values in MATLAB are returned? Are they copied or passed by reference?
take a look at this example with matrix A:
function main
A = foo(10);
return;
end
function [resultMatrix] = foo(count)
resultMatrix = zeros(count, count);
return;
end
Does the copy operation take place when function returns matrix and assigns it to variable A ?
MATLAB uses a system known as copy-on-write in which a copy of the data is only made when it is necessary (i.e. when the data is modified). When returning a variable from a function, it is not modified between when it was created inside of the function and when it was stored in a different variable by the calling function. So in your case, you can think of the variable as being passed by reference. Once the data is modified, however, a copy will be made
You can check this behavior using format debug which will actually tell us the memory location of the data (detailed more in this post)
So if we modify your code slightly so that we print the memory location of each variable we can track when a copy is made
function main()
A = foo(10);
% Print the address of the variable A
fprintf('Address of A in calling function: %s\n', address(A));
% Modify A
B = A + 1;
% Print the address of the variable B
fprintf('Address of B in calling function: %s\n', address(B));
end
function result = foo(count)
result = zeros(count);
% Print the address of the variable inside of the function
fprintf('Address of result in foo: %s\n', address(result));
end
function loc = address(x)
% Store the current display format
fmt = get(0, 'format');
% Turn on debugging display and parse it
format debug
loc = regexp(evalc('disp(x)'), '(?<=pr\s*=\s*)[a-z0-9]*', 'match', 'once');
% Revert the display format to what it was
format(fmt);
end
And this yields the following (or similar) output
Address of result in foo: 7f96d9d591c0
Address of A in calling function: 7f96d9d591c0
Address of B in calling function: 7f96d9c74400
As a side-note, you don't need to explicitly use return in your case since the function will naturally return when it encounters the end. return is only necessary when you need to use it to alter the flow of your program and exit a function pre-maturely.

Stumped trying to implement Save/Load object functionality in a MATLAB UI

I am trying to implement save/load functions in a MATLAB (R2009a) UI. My object implements a layout function that generates a user interface for the object. I am trying to implement the callbacks for the save/load buttons. The save button works and save the object out to a MAT file which can be loaded later.
My problem is implementing the callback for the load button. I cannot seem to get the load to load the data from the MAT file and update the properties of the new object. Any suggestions on where I am going wrong along with suggestions on how I might proceed is greatly appreciated.
The important code is my class definition file of course my actual object implements many more properties and methods but here is a skeleton of what I have
classdef myObj<handle
properties
image % property holds a matlab image matrix
objCount % number of objects in image
end
properties(Transient=true)
parent
children
end
methods
function myObj
% empty constructor
end
function load_object(self)
% ask user for file
[fileName, pathToFile]=uigetfile('*.mat','Select .mat file');
tmp = load(fullfile(pathToFile,fileName);
if isfield(tmp,'obj')
self = tmp.obj;
end
end
LayoutFcn(self) % UI layout function
end
end
The UI layout is defined in a seperate file LayoutFcn.m which basically looks like
function LayoutFcn(self)
% create figure window and add various UI elements
...
% create load button
self.children(end+1) = uipushtool('Parent',hToolbar, ... % set parent to current toolbar
'CData',iconRead('open-document.png'), ... % read icon image from file
'Tag','uiLoad', ...
'ClickedCallback',#(hObj,event)loadingMyObject(self,hObj,event));
% create save button
self.children(end+1) = uipushtool('Parent',hToolbar, ... % set parent to current toolbar
'CData',iconRead('save-document.png'), ... % read icon image from file
'Tag','uiSave', ...
'ClickedCallback',#(hObj,event)savingMyObject(self,hObj,event));
...
end
function loadingMyObject(self,hObj,event)
self.load_object; % call load_object method defined above in class definition
end
function savingMyObject(self,hObj,event)
[fileName,pathName]=uiputfile('.mat','Save object to MAT file');
obj = self;
save(fullfile(pahtName,fileName),'obj')
end
Note: I am using MATLAB R2009a.
The code doesn't throw any errors. The way I wrote the code the parent object (represented by self) does not get updated after the call to LOAD in the method load_object. SO, this has the desired effect:
>> var = myObj;
>> var.load_object;
However, if I use the loadingMyObject callback defined in LayoutFcn.m in this fashion
>> var = myObjl
>> var.LayoutFcn
-> click Load button to call _loadingMyObject_
doesn't affect var properties. That is var will still have its default property values after clicking the Load button.
Changing the load methods to use set as suggested by gnovice throws the following error
??? Error using ==> set
Conversion to double from FujiCalibration is not possible.
even though I have set/get methods for each property; as in
method set.image(self,II)
% ... some data validation code ...
self.image = II
end
Using a loop to set each field as suggested by Mr Fooz is not really an option as my full class has public constant that throw an error when they are set.
I am looking for a solution that would avoid me having to hand code setting each field individually. Although at this point it seems like the only possibility.
I believe Mr Fooz is right. The self variable passed to load_object is an object of type "myObj", but the line:
self = tmp.obj;
is simply overwriting the self variable with the structure stored in tmp.obj. Doing:
self.image = tmp.obj.image;
should instead invoke a set operator for the image property of object self. In the MATLAB documentation there is a sample class definition with a method called "set.OfficeNumber" that illustrates this.
In addition, the following line in your function savingMyObject may be unnecessary:
obj = self;
I think it might make most sense (and make the code a little clearer) if you used the name "obj" in place of the word "self" within your class code (as the documentation tends to do). "self" doesn't appear to be any kind of special keyword in MATLAB (like it may be in other languages). It's just another variable as far as I can tell. =)
EDIT #1:
If the prospect of having to set each property individually in your load_object method doesn't sound like fun, one way around it is if you have a SET method for your object that is designed like the SET method for handle graphics. That SET command can accept a structure input where each field name is a property name and each field value is the new value for that property. Then you would have one call like:
set(self,tmp.obj);
Quite a bit shorter, especially if you have lots of properties to set. Of course, you'd then have to write the new SET method for your object, but the shortened syntax may be worth the extra work if it comes in handy elsewhere too. =)
EDIT #2:
You may be able to use the loop Mr Fooz suggested in conjunction with a try/catch block:
fn = fieldnames(tmp.obj);
for i = 1:numel(fn),
try
self.(fn{i}) = tmp.obj.(fn{i});
catch
% Throw a warning here, or potentially just do nothing.
end
end
Don't assign values to self. All that does is replace the binding to the self variable in the scope of the method call. It does not call a magical copy constructor to replace the object reference in the caller. Instead, copy the fields into self. Try something like:
if isfield(tmp,'obj')
self.image = tmp.obj.image;
self.objCount = tmp.obj.objCount;
end
Combining Mr Fooz's and gnovice's suggestions, I added a SET function with the following definition
function set(self,varargin)
if isa(varargin{1},'FujiCalibration')
tmp = varargin{1};
fns = fieldnames(self);
for i = 1:length(fns)
if strcmpi(fns{i}(1:2),'p_')
self.(fns{i}) = tmp.(fns{i});
end
end
self.calibImage = tmp.calibImage;
else
proplist=fields(self);
for n=1:2:length(varargin)
tmp = proplist(strcmpi(proplist,varargin{n}));
value = varargin{n+1};
switch length(tmp)
case 0
msg = char(strcat('There is no ''', varargin{n}, '''property'));
error('FujiCalibration:setPropertyChk',msg)
case 1
tmp = char(tmp);
self.(tmp) = value;
end
end
end
end
I then modified the load_object method as suggested by gnovice by changing
self = tmp.obj
to
set(self,tmp.obj).
I need to make sure that properties with values I want to persist are prefixed with 'p_'.
Thanks to gnovice and Mr Fooz for their answers.