Matlab saving Guide input data to use it on calculation - matlab

I have problem using Guide.
I want users to type data in the edit box of guide.
Then for example I want Matlab to save that value as Velocity
and use that value to calculate many other things using it.
What I got stuck was like this
I used assignin function
function edit1_Callback(hObject, eventdata, handles)
Vel=get(handles.edit1, 'String');
assignin('base', 'Vel', Vel);
Than I ran it on command line.
I entered 8 and it gave me
a = 8
so I typed a+4
Than I gives me 68 or something.
I want 12 for my answer. What can I do??
Thanks advance.

a is a character/string you need to call str2num first.

Related

For Loop within Matlab GUIDE

I have Matlab GUI that uses push button that executes certain code.
all of that works, except that when code reaches for loop, execution does not seem to enter that.
1) Any idea how for loop is implemented within framework of Matlab GUIDE code?
2) is there a way to debug GUI code ( only way I could was trough 'disp' statements,) using breakpoints, as when I run the GUI, breakpoints get removed.
after having read the solutions, I found that
(1) happened because the for loop index was not changing as length of array
that I was indexing on, was not changing. I explain this in the code.
(2) My bad, I was putting breakpoints before running the GUI, when I did the other way around, it breaks fine.
% Opening func
function Regression_OpeningFcn(hObject, ~, handles, varargin)
NoiseMin = -12;
NoiseMax = 10;
NoiseRes = 2;
handles.noiseMin = NoiseMin;
handles.noiseMax = NoiseMax;
handles.noiseRes = NoiseRes;
%**this executed when value changed in edit text box***
function noiseMinDbEditText_Callback(~, ~, handles)
handles.noiseMin = str2num(get(handles.noiseMinDbEditText,'String'));
% When GUI is running, following shows change from -12 sucessfully
disp(strcat('Noise Min = ',num2str(handles.noiseMin)));
function noiseMinDbEditText_CreateFcn(hObject, ~, ~)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%Similar code for noiseMax and noiseRes(not shown here)
`% Here, code enters the Pushbutton callback
function StartRegressionPushButton_Callback(~, ~, handles)
snr_res = handles.noiseRes;
% here, snr_vecs still shows [-12 2 10]
snr_vecs = [handles.noiseMin:handles.noiseRes:handles.noiseMax];
So, basically, when GUI runs, entering and changing the values in text box corresponding to min, max and res snr variables shows me the change, but as soon as I enter the pushbutton dialog box, the changed values( that were captured in global variable "handles") do not show up as I break in the code there.
Any help with this? [for loop problem arose as I was indexing based on snr_vecs array, which is not changing, and so for loop was executing,but not as it should be]
sedy
Using Matlab guide
Guide is basically only a tool to create fig. files. All you can do with guide you could do yourself programmatically. Creating ui-elements works by hand just as easy as with guide (I actually prefere creating gui elements programmatically, since I think guide is very poorly coded)...
Every guide-elements has its callbacks which have to be coded somewhere, usually (I think 100% of the time) the fig file has the same name as the .m file. Find the corresponding .m-file and go to the callback you are interessted in. There you can place breakpoints just as easy as in any other piece of code.
Note: you can even change the code without having to reopen the fig file!
For loops or anything that works in regular code works for ui-element code.
The reason for handles not getting updated was missing following statement at end of function callback whose variable needs to be used in other callback.
guidata(hObject,handles);
I fixed that and it works nicely.
sedy

Running Functions in GUI matlab

Continuing my struggle against GUI's, I have run into another road block.
Ive successfully created a button that opens a file as a string, and places it in a text box in my GUI like so.
[filename, pathname] = ...
uigetfile({'*.m';'*.mdl';'*.mat';'*.*'},'File Selector');
set(handles.Textbox1, 'string', fullfile(pathname,filename));
But now I cannot seem to use a function on the acquired file. Ive tried doing
str = get(handles.Textbox1,'string');
Histogram(str); %Histogram is a function that I created.
But im getting the following errors
??? Error using ==> Histogram Too many input arguments.
Error in ==> VarunGUI>pushbutton2_Callback at 94 Histogram(str);
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> VarunGUI at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==>
#(hObject,eventdata)VarunGUI('pushbutton2_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
Is my code for calling the function to blame, or is the function itself? I'm having trouble understanding how to alter the function to work on the called image, so that may be my problem, the function begins with the following code.
function Histogram
clear;
clc;
fid = fopen('');
myimage = fread(fid, [512, 683], '*uint8');
fclose(fid);
Is there a certain variable I need to place in the '' to make the GUI act in the manner to which I would like it? Question ran a little long, but please tell me if there is anything else you need to see in order to assist me, any guidance or tips would be great. Thanks!
Your Histogram function doesn't have an input, so it fails when you call it : Histogram(str)
You're problem is that call Histogram and pass it str:
Histogram(str)
But you don't define Histogram to expect input:
function Histogram
What you need is something like this:
function Histogram(str)
% do something with str
I got this y'all!
Change your histogram function to this: (literally copy and paste what's below)
function Histogram(str) %Add input argument
%clear %DO NOT USE CLEAR in a function, the benefit of using a function is you don't have to %clear anything :)
clc;
fid = fopen(str); %Use input argument
myimage = fread(fid, [512, 683]); %take off *uint8
fclose(fid);
Read MATLAB's documentation, it is fantastic, and would allow you to see why fread and uint8 don't go together in a matter of seconds (seriously less than 20 seconds would give you your answer) and it would also solve all your other extremely basic issues you are having.

the push button in matlab exe file doesn't work

I developed a Matlab GUI program which it has four editbox & one pushbutton; my application works properly when I run it with Matlab software, but after converting it to exe file (standalone), the pushbutton doesn't work, means it doesn't show the output in 'Result' editbox. so what's the problem?
here is my pushbutton code:
function btnCal_Callback(hObject, eventdata, handles)
a=str2num(get(handles.txbLow,'string'));
b=str2num(get(handles.txbHi,'string'));
f=get(handles.txbForm,'string');
x=0.5*((b-a)*(-1*(3/5)^0.5)+b+a);
g=subs(f,'x',x);
sum=(g)*(5/9);
x=0.5*(b+a);
g=subs(f,'x',x);
sum=sum+(g)*(8/9);
x=.5*((b-a)*((3/5)^.5)+b+a);
g=subs(f,'x',x);
sum=sum+g*(5/9);
result=sum*((b-a)/2);
set(handles.txbResult,'string',result);
First, I'm a bit confused with
result=sum*((b-a)/2); % "result" is numeric
set(handles.txbResult,'string',result); % "result" should be string
Next, just as a hint. To "debug" your deployed code, try to launch your exe from cmd, in this case, you would see some messages there, and they might help.
your 'result' needs to be either double, char, or cell. You can do this by e.g.
set(handles.txbResult,'String',char(result);
However: I got exactly the same problem with a very similar code on my Mac. The Application runs very well if executed via "run" in Matlab, but once I compiled it to a standalone.app one hears this error-sound when pushing the button, nothing else is happening.
Trying to set the 'result' variable as "global" helped solving this problem for another program that I wrote (a very simple "calculate a+b" thing), but not for the mentioned slightly more complex code (3 instead of 2 inputs and 3 outputs instead of 1).
The super simple code which is working:
function pushbutton1_Callback(hObject, eventdata, handles) %the button to push
...some code...
global statText;
set(statText,'String',char(output));
function text1_CreateFcn(hObject, eventdata, handles) %the outputfield
global statText;
statText = hObject;

How to intercept key strokes in Matlab while GUI is running

Do you know how to read keyboard strokes into Matlab while a Matlab gui is running? (I.e., without using the "input" function which sends a prompt to the command window and needs you to press return).
We would like to avoid using a mex function if possible.
You would first have to declare your figure by handle:
fig = figure;
then you can set properties (in quotes below) to activate functions that you've written to respond to user interactions (with the # signs):
set(fig,'KeyPressFcn',#keyDownListener)
set(fig, 'KeyReleaseFcn', #keyUpListener);
set(fig,'WindowButtonDownFcn', #mouseDownListener);
set(fig,'WindowButtonUpFcn', #mouseUpListener);
set(fig,'WindowButtonMotionFcn', #mouseMoveListener);
The above example is from shooter03.m a MATLAB space shooter, an excellent source (from the matlab file exchange) for many aspects of user object interaction in MATLAB:
http://www.mathworks.com/matlabcentral/fileexchange/31330-daves-matlab-shooter/content/shooter03/shooter03.m
If your GUI is based on a figure, you can use the figure property keypressfcn to define a callback function that handles keyboard inputs. See the matlab help for further descriptions: http://www.mathworks.de/help/techdoc/ref/figure_props.html#KeyPressFcn
Try:
hf = figure;
get(hf,'CurrentCharacter')

Matlab GUI: referencing an existing object handle using a variable

I am currently working on my matlab final project for school. I consider myself fairly knowledgeable and proficient when it comes to programming.. but Matlab simply has TOO many oddities.
The fundamental question (realized this after finding the answer)! How can I use a variable in a call to a gui handle object
without the name of the variable being used instead of the value?
In other words: Use a variable in a field name (If I had known it was this simple I wouldn't of asked)
My project is building a simple rendition of the age old 'Battleship' game.
My issue: I currently 5 objects (axes) for the ship pieces. They are selected one at a time to be moved into another location(the grid). I am able to use the setpixelposition to move each object after a button click.
Right now under the button click, I have something like this
function btnPlaceShip_Callback(hObject, eventdata, handles)
%Store the current selected ship(passed from an onclick to a label)
ship = get(handles.lblSelectedShip,'string');
%I have tried everything I could think of, but basically I want to achieve the
%following
setpixelposition(handles.ship, [0 250 50 250])
%where the variable 'ship' contains the name of the object.
In other words, the var ship = 'shipAircraftCarrier', and..
setpixelposition(handles.shipAircraftCarrier, [0 250 50 250])
works!(sets the position of the specific ship indicated). Using the variable ship, however, matlab takes the string literally and not for its value. It would be extremely convenient to use the variable instead!
If anyone have any solutions, I would be grateful. I have scoured the web but perhaps I am missing some fundamental understanding of the Matlab GUI stuff - The matlab help documents are very non-descriptive and are not of much help.
As mentioned by others use dynamic fieldnames. Whilst not having the code to test it I believe that simply putting brackets around the ship will substitute the string in to the structure name, thus
setpixelposition(handles.(ship), [0 250 50 250])
Try to avoid the use of eval() if at all possible.
You can do this using the eval function, but you need to be careful about string injections:
setpixelposition(eval(strcat('handles.',ship)), [0 250 50 250])
You can use dynamic fieldnames or getfield. Field indexing using identifiers vs strings is quite similar in Matlab structs and Javascript objects.
Matlab:
fromId = handles.shipAircraftCarrier; %identifier
fromString = handles.('shipAircraftCarrier'); %string
Javascript:
var fromId = handles.shipAircraftCarrier; //identifier
var fromString = handles["shipAircraftCarrier"]; //string