Sorry for the delay in postings, but many of us are in the state of transition, whether its school, weddings or work. As a simple tutorial to get back into the swing of things, let’s look at several different ways of requesting user input in your MATLAB programs. While you will often need to display information to the user, you will have to request data from them as well. There are several options available to you, and we will run through many of them here. The most basic of which is the command line based “input”.

Take the example of a program where you are evaluating the body mass index (BMI) of an individual. One way this can often be done is through a function such as calc_bmi.

function bmi = calc_bmi(weight,height) % Calculate the body mass index of an individual. % Given that weight is in kilograms and height is in meters. bmi = weight/height^2;

While this is certainly a viable solution, often the user will not explicitly provide the weight and height into the argument fields. Let’s see how we can get around this using the command nargin and input. These lines will be added after the comments and before the bmi calculation.

if nargin == 0 % Check the number of input arguments (nargin) weight = input('Enter your weight in kilograms: '); height = input('Enter your height in meters: '); end

Now if the user runs the following commands at the command prompt, they will be queried as follows:

>> calc_bmi Enter your weight in kilograms: 71.1 Enter your height in meters: 1.65 ans = 26.1157

Let’s say you want to input non-numerical data such as a string. Then include the following at the end of your script instead:

name = input('What is your name? :','s'); % 's' indicates that name is a string. bmi = weight/height^2; disp(['Hello ',name,' your BMI is : ', bmi,' kg/m^2']);

The ‘s’ option will save the variable ‘name’ as a String now.

Another method to gather user information, is through the use of a input dialog box, and the command inputdlg:

prompt={'Enter your weight:','Enter your height:','Enter your name:'}; % Create all your text fields with the questions specified by the variable prompt. title='BMI calculator'; % The main title of your input dialog interface. answer=inputdlg(prompt,title); weight = str2num(answer{1}); height = str2num(answer{2}); % Convert these values to a number using str2num. name = answer{3};

This will create the following dialog box which allows the user to enter information as needed:

There are several other dialog box options that you can use which we will not cover in depth here. If you want to learn more, the ‘help’ function can be your friend. They do take in the same options, such as ‘prompt’ and ‘title’, with a couple of useful dialog input commands being:

‘listdlg’, where the user needs to choose options from a number of selected number of predefined options.

‘questdlg’, which creates up to 3 custom buttons for the user to choose from.

Finally, sometimes you require the user to select a certain portion of a graph to be analyzed further. This can be done through the use of the command ‘ginput’.

The format for ginput is [x,y,mouse] = ginput(N), where (x,y) are the coordinates on the cartesian plane, mouse indicates which mouse button was pressed and N specifies the number of inputs you which to acquire. The arguments ‘mouse’ and ‘N’ are optional, with ‘N’ left blank indicating that you do not want to explicitly state the number of inputs, but rather wish to wait until the user presses the ‘return’ key.

For example, creating the following plot, and requesting two user clicks…

x = 0:0.01:3.14159; plot(sin(x)); [x_coord y_coord] = ginput(2);

… will create the following plot:

and the following values (if you clicked in those locations).

x_coord = 109.2742 42.3387 y_coord = 0.0804 0.4254

As a word of caution. If you need precise locations, be sure to zoom in on data and select appropriately, otherwise you will just select any coordinate on the graph. Also, be aware of the axes. For example in this situation, x_coord gives us numbers up to ~110. In order to determine the actual x value, you can run

x(floor(x_coord))

Also, you’ll notice that the value for

sin(x(floor(x_coord)))

does not necessary give you the same results as y_coord. This is because I might not have clicked exactly on the curve! So be careful in your graphical inputs.

If you have any suggestions or comments, please don’t hesitate to contact us.

I try run the matlab coding for box.. After I fill all the data, and click ok, why it did not display the result for my BMI. is it, I have miss some codding. It was very interesting codding..

when you output the bmi, it is variable which represents a number so you have to apply num2str(bmi). Then it will output.

You are required to design, code, and test a Matlab program that performs the followings:

1. Request the user to enter a function

2. Request the user to enter the minimum and maximum values the function can take (the function domain)

3. Request the user to enter the number of points

4. Plot the graph of the function on the function domain using the number of points given

p/s : how to solve it?

Write down a function file.

Give options to user to choose the method of finding area of a triangle. (Give as many as you can)

After choosing the option, user will input the data according to formula.

The area of triangle will come out as output.

thanks for the dialog box information. if i want to input either of 2/3 values in one variable? is there any way to do it?

example – w = input

N = input

[W]= w*ones(N)

or

w1 = input

wn = input

Wn = w*ones(N-1,1)

W = [w1;Wn]

or

w1 = input

w2 = input…….

…..

wn = input

W = [w1:wn]

then i want to use either of one data as W vector

tnx

Would you be able to help me out. I am trying to write a user input interval code in matlab and I keep getting error saying * improper use. Here is my code…

clear

prompt=’T zeta';

T=v1;

zeta=v2, i.e. [0,4*pi];

zeta=input(v2);

result=input(zeta);

v1-v2;

We=(1-(2*zeta.^2));

Wd=sqrt(1-zeta.^2);

x=-4:.001:4;

y=exp(-zeta.*T)*(2*zeta.*cos(Wd.*T)+

((We./Wd).*sin(Wd.*T)));

Any help in the right direction would be greatly appreciated. Thanks!

I’m not sure what you are trying to do with the following:

zeta=input(v2);

result=input(zeta);

The first argument for input needs to be a string, so in this case v2, would have to be a string. Maybe zeta = input(prompt)?

As for the second line, what are you trying to do here? The zeta you return in the first line will be the value inputted by your user…

I currently have an inputdlg in my program. I am trying to instead have this input box be seen in the same window as an output table (pre-written), and then not dissapear when an input is entered, but rather stay up until another input is entered. Is there a way to do this?? Thanks.

I appreciate any help!

hi im writing a program this it so far.

F=inputdlg(‘Please input the equation you wish to solve by the trisection method’)

%Assigning initial values to a and b, and max number of iterations and tolerance.

a=input(‘Please input first interval’)

b=input(‘Please input second interval’)

Fa=F(a)

Fb=F(b)

i would like matlab to put the value of A inputted, in the function or equation that was also inputted

You could use something like:

Fa = subs(F,a) to solve the equation.

If the function F has multiple variables, something like follows could work:

subs(F,{x,y},{a,b})

plz help me how to Adaptive Subcarrier Allocation is possible on MATLAb

how to let the user an array input in an edit box?

example : 1 2 3 4 2 1 in the edit box

Hello! I’m using listdlg() and I seemed to get the appearance exactly how I wanted it. I do however need my program to be able to pick up which selections the user has made rather than just the quantity. Running my program and making selections myself shows me that only a value of ‘1’ is stored for each selection made, but knowing the exact position or possibly the name of the selection made (i.e. course “MA 241″) would be much more useful. Can anyone tell me how to store selections to the variable which the listdlg is assigned?

Is there a way to make several boxes in one line? I have really too many inputs and I want to have one large screen not scroll down.

Not sure exactly what you want, but do you mean something like:

inputdlg({‘a’,’b’,’c’}, ‘Test’, [5 100])

where the third argument specifies the number of rows/columns?

You can also set the horizontal resize option to be ‘on’ (it is ‘off’ by default).

options.Resize = ‘on’.

Then run the following:

inputdlg({‘a’,’b’,’c’}, ‘Test’, 5, {”,”,”}, options)

Hi,

I need to write a program that asks the user for the function to be plotted. How can I do this and let the program know that it is a function?

Thanks!

Take a look at our current post, will explain symbolics a little bit.

Could do something as follows:

funcPlot = inputdlg(‘Enter the function to be plotted’);

Say the user typed in something like: sin(x) + x^3

Then you could plot this function using: ezplot(funcPlot{1});

Is there a way to allow the user to input either mouse or text data? For instance can I show the sine plot and ask the user for the x value they want and allow them to either click the location they want or enter the coordinates in a dialog? (I was initially thinking that making a non-modal inputdlg and then putting a ginput right after it would do this but that just requires the user to enter it twice.) Thanks for your help.

thanks that was helpful. Can you please post some helpful info about how to use the listdlg function, giveng me trouble.Thanks in advance.

Chantell,

The listdlg function takes in at least one parameter(2 inputs), {‘ListString’, S}, and outputs two values (location of the selected value, and if a selection was made).

If we define S as S = {‘Blue’,’Green’,’Red’}. Then we can create a dialog box as follows:

[a b] = listdlg(‘PromptString’,’Select your favorite Color:’,’ListString’,S)

If I were to select Green and click OK, or double click Green:

a = 2 (as green is the 2nd value in the string array S) and

b = 1 (as a valid value was selected).

Note that the parameter ‘PromptString’ was not necessary, and other parameters, specifically: ‘SelectionMode’, ‘ListSize’,’InitialValue’,’Name’,’OKString’,’CancelString’ can also be specified. If you need assistance on those, let me know or look up help listdlg.

Take care,

Vipul

Hello,

When I write:

weight = input(‘Please enter weight in kilograms: ‘);

height = input(‘Please enter height in meters: ‘);

I run it and only get asked the height, why is that?

Yael,

I am not sure why you are not seeing only the height question. Can you try running one line at a time and seeing how matlab responds? You should then have the variables weight and height saved in the workspace.

Vipul

i am taking 4 inputs using inputdlg function & then trying to call a function with this 4 parameters, but getting a error.

prompt = {‘Sx’,’Sy’,’f’,’theta’};

text=’Please input the Gabor Filters parameters';

text1=’Enhancement by Gabor Filter';

h=uicontrol(FigWin,…

‘Style’,’pushbutton’,…

‘Position’,[0,280,80,20],…

‘String’,’GF’,…

‘Callback’,…

[‘w=inputdlg(prompt,text,1);w=str2double(w);’…

‘subplot(AxesHandle1);image1=gaborfilter1(image1,w{1},w{2},w{3},w{4});imagesc(image1);title(text_fft);’]);

but getting an error saying “Cell contents reference from a non-cell array object”

Chirag, sorry you’re getting those errors. One of your commands is attempting to access a non-cell array object. I don’t have all of your other functions (i.e. gaborfilter1) or variables, but at first glance, it looks like ‘w’ has been converted to a double. When you access ‘w’ now, you can’t use {}, instead use ‘w(1)’.

Hi,

Thank you very much for the detailed Information for Input dialog,it’s really helpful.Could you help me to write the codes for saving the Input data and Bmi processed data (name,age,height,weight are the Input data BMI is the output data) from GUI mat-lab to Excel spreadsheet.Thanks in advance.

Are you thinking of using something like the command ‘xlswrite’? Take a look at that function, and see where you can get. If not let me know. Thanks.

i need to give input to the program as a signal and have to filter it.. pls help me write the code..

That is very helpfull.

how to enter multiple values in multiple form into a single variable…..?

EX-

busa=input(‘Enter the pd,qd,pqpg,pqqg,pvpg,ps,vv,ymag,yth values :’)

where

pd is int

qd is array

pqpg and pqqg is matrix form …….

I would recommend storing several different data types into a cell array if this is your plan. You can use ‘inputdlg’ to accomplish this if need be. If anyone else has suggestions, please feel free to respond.

Before to use disp I had transform “bmi” in a string.

great article thanks for the sharing ,keep doing great work

Thanks, it helped me. Keep on the good job.