MATLAB : how to pass the string variable from a function to GUI? - matlab

For example, I have a function called function1 which has a variable, say str1 which holds a string.
I have also a GUI created by using MATLAB's GUIDE with the tag called textgui that has a static text tagged text1.
How do I pass the string str1 to the GUI so that when I run the GUI the static text text1 will show the string of the variable str1?
EDIT : function1 will generate the string str1 and then call the GUI textgui to show the string
EDIT2 : below is the code of function1 and an image of textgui.
str1 = 'some text here';
textgui; % runs the GUI
what should I do so that when I run function1, the static text in the GUI will show as the string which str1 holds?
Thanks for help!

When you set the value of str1, you just want to update the String property of the static text object using this variable.
str1 = 'my string';
set(handles.text1, 'String', str1)
If your function1 isn't a callback of your GUI, you can always use findall to find the handle to the static text object and set it that way.
str1 = 'my string';
set(findall(0, 'tag', 'text1'), 'string', str1)
If your function is initializing textgui, then you can pass the string directly to the GUI function as an input parameter:
str1 = 'my string';
textgui(str1);
This requires you to modify the textgui_OpeningFcn defined by GUIDE to process the input argument (stored in varargin):
function textgui_OpeningFcn(hObject, eventdata, handles, varargin)
set(handles.text1, 'String', varargin{1})
% Leave the other stuff that GUIDE sets alone
end

Related

Octave: how to answer an input() prompt with a variable from my workspace?

In the command window, I define a variable var = 10. I call My_Function, and it says "Input a value: ". I want to respond " var " and have it evaluate that as 10. Is there a way to pass in the variable through input() or any other similar command?
I know how to do My_Function(var) and pass it in that way, but is there a way to take in variables at a user input prompt during the function?
This is how the input function behaves by default, it runs the content user wrote as it is code. Make sure you are not using the 's' parameter that is commonly used to make octave interpret the input as text, instead of code.
>> var = 1;
>> x = input('Please enter the value: ')
Please enter the value: var
x = 1
Since it runs as a code, you can also do any operation here, including calling other functions.
>> x = input('Please enter the value: ')
Please enter the value: sind(30)
x = 0.5000
This works on the current workspace. If you want to reach the variables in another workspace, like the base one, you need to explicitly define that the input function should run on the base workspace.
function [] = My_Function ()
x = evalin("base","input('Please enter the value: ')");
disp(x)
endfunction
>> My_Function()
Please enter the value: var
1
In MATLAB you can make My_Function a nested function, so all the variables in the caller workspace are visible inside the nested function. E.g.,
function Top_Function
var = 10;
result = My_Function
function x = My_Function % This is nested inside Top_Function
x = input('Input a value: ');
end
end
My_Function( ) will see all the variables in Top_Function unless they are shadowed by My_Function variables. So you can use var in the input( ) statement and it will evaluate to 10 in the above example.

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.

Custom class containing a scalar categorical displays as "[1x1 categorical]" instead of displaying the category

On MATLAB R2014b, when you have a struct (or custom class) having a field that is a scalar categorical, when displaying the struct it will show [1x1 categorical] instead of what I want to achieve as shown below.
MWE:
struct.field = categorical({'category'})
Output:
struct =
field: [1x1 categorical]
My desired output:
struct =
field: category
or:
struct =
field: category [1x1 categorical]
I want this, because I'm writing some classes that have a categorical property that is always scalar; because I know this by definition, I don't need the objects' category to be displayed as [1x1 categorical]. When displaying the custom objects, I'd like it to show the category instead.
I could overload disp in my class methods, but then I'd need to rewrite a lot of displaying code from disp itself instead of merely changing the way a scalar categorical in a struct field shows.
Any ideas on how to achieve this? If your answer involves overloading disp in the class definition, then I want to see how you could display the object's other properties like a normal disp(obj) would, in addition to displaying the categorical property the way I want. Any ideas or thoughts you have might help me write my own answer, so please share any.
After playing around with this for a while, I think I finally have something that works for displaying these scalar categorical values within a custom class.
The basic idea is that I overload the get method for the property that is holding the categorical. I can then check the call stack to see what is trying to get the value of the variable. If it's our overloaded disp method (which is called any time we want to display our class), then I return the category name if it's only a scalar categorical. Otherwise, I return the value of the property itself (as a categorical).
It's definitely not the most elegant due to it's reliance on dbstack but it seems to work quite well.
classdef categoryclass < handle
properties
a = categorical({'category'});
end
methods
% Get Method for "a" property
function res = get.a(self)
% Get the call stack to determine *what* called this
stack = dbstack();
methodname = sprintf('%s.disp', class(self));
% If it is a scalar and it was called by our overloaded display
% method, then return the category name
if isscalar(self.a) && isa(self.a, 'categorical') && ...
strcmp(methodname, stack(end).name)
res = categories(self.a);
res = res{1};
% Otherwise return just the value itself
else
res = self.a;
end
end
% This ensure that disp() shows up in the stack
function disp(self)
% Simply call the built-in display function
builtin('disp', self);
end
end
end
Now if we try this out.
cls = categoryclass()
categoryclass with properties:
a: 'category'
Check that when we request the value we actually get a categorical.
class(cls.a)
ans =
categorical
Now change the value of it.
cls.a = categorical({'another category'})
categoryclass with properties:
a: 'another category'
Now use two categories
cls.a = categorical({'one', 'two'})
categoryclass with properties:
a: [1x2 categorical]
NOTE: This only appears to be an issue in R2014b and R2015a. It was fixed in all later releases.
It's been a while, but today I needed this again. I thought of another way to display scalar categorical variables. The following example class does the trick.
classdef dispfmtTest < matlab.mixin.Copyable
properties
prop = categorical(1) % default value is a scalar categorical
end
methods
function dispfmt(obj) % dispfmtTest object to display format
obj.prop = char(obj.prop); % convert to char type
end
function disp(self)
obj = copy(self); % copy is provided by superclass
dispfmt(obj)
disp#matlab.mixin.Copyable(obj) % call superclass disp
delete(obj)
end
end
end
The dispfmtTest class is a subclass of matlab.mixin.Copyable, which is in turn a subclass of handle. It provides the copy method to the disfmtTest class, which is used to temporarily create a copy of which the value of property prop is changed to whatever desired display format in method dispfmt. Then, the modified copy of the object is displayed using the regular disp function as provided by matlab.mixin.Copyable.
Demo
Running obj = dispfmtTest yields
d =
dispfmtTest with properties:
prop: '1'
and class(d.prop) yields
ans =
categorical
This is the behaviour as I expected. Support for array properties can be achieved too using isscalar.

MATLAB GUI - bring up a string

i' m try to create a simplex and fast gui on matlab. I made a button with a callback function, but I don' t know how to bring up a string that depends upon the result of the function. For example if the result of the function is 1, must appear the string "All ok!", if the result of the function is 0, must appear the string "It' s wrong!!!".
You can create a Static Text object or an inactive Edit Text object and modify the String property from your script with:
set(handles.edit_text, 'String', 'your_string')
An alternative to the static/edit uicontrol is to use a msgbox or an errordlg to display the result to the user depending on the result of your function.
if myFunction
msgbox ( 'All Ok' );
else
errordlg ( 'Error in Function', 'Error' )
end

routine to either evaluate code or transmit via udp

I have a set of code that, depending on how the program is initiated, will either be executed locally or sent to a remote machine for execution. The ideal way I imagine this could work would look something like the following:
line_of_code = 'do_something_or_other();';
if execute_remotely
send_via_udp(line_of_code);
else
eval(line_of_code);
end
The thing is, I know that the eval() function is ridiculously inefficient. On the other hand, if I write out line_of_code in each section of the if block, that opens the door for errors. Is there any other way that I can do this more efficiently than by simply using eval()?
EDIT: After more consideration and some discussion in the comments, I have my doubts that function handles can be transmitted via UDP. I'm therefore updating my answer, instead suggesting the use of the function FUNC2STR to convert the function handle to a string for transmission, then using the function STR2FUNC to convert it back to a function handle again after transmission...
To get around using EVAL, you can use a function handle instead of storing the line of code to be executed in a string:
fcnToEvaluate = #do_something_or_other; %# Get a handle to the function
if execute_remotely
fcnString = func2str(fcnToEvaluate); %# Construct a function name string
%# from the function handle
send_via_udp(fcnString); %# Pass the function name string
else
fcnToEvaluate(); %# Evaluate the function
end
The above assumes that the function do_something_or_other already exists. You can then do something like the following on the remote system:
fcnString = receive_via_udp(); %# Get the function name string
fcnToEvaluate = str2func(fcnString); %# Construct a function handle from
%# the function name string
fcnToEvaluate(); %# Evaluate the function
As long as the code (i.e. m-file) for the function do_something_or_other exists on both the local and remote systems, I think this should work. Note that you could also use FEVAL to evaluate the function name string instead of converting it to a function handle first.
If you need to create a function on the fly, you can initialize fcnToEvaluate as an anonymous function in your code:
fcnToEvaluate = #() disp('Hello World!'); %# Create an anonymous function
And the code to send, receive, and evaluate this should be the same as above.
If you have arguments to pass to your function as well, you can place the function handle and input arguments into a cell array. For example:
fcnToEvaluate = #(x,y) x+y; %# An anonymous function to add 2 values
inArg1 = 2; %# First input argument
inArg2 = 5; %# Second input argument
cellArray = {fcnToEvaluate inArg1 inArg2}; %# Create a cell array
if execute_remotely
cellArray{1} = func2str(cellArray{1}); %# Construct a function name string
%# from the function handle
send_via_udp(cellArray); %# Pass the cell array
else
cellArray{1}(cellArray{2:end}); %# Evaluate the function with the inputs
end
In this case, the code for send_via_udp may have to break the cell array up and send each cell separately. When received, the function name string will again have to be converted back to a function handle using STR2FUNC.