Difference between revisions of "MATLAB:Flexible Programming"

From PrattWiki
Jump to navigation Jump to search
m
m
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
\section{Using Strings}
+
This page covers some ways [[MATLAB]] programs can be made more flexible by using strings. 
Matlab's ability to use strings can come in very handy when writing
+
MATLAB's ability to use strings can come in very handy when writing
programs to solve engineering problems.  For some assignments, you will  
+
programs to solve engineering problems.  For some programs, you will  
want to use Matlab's {\tt sprintf} and {\tt eval} functions along
+
want to use MATLAB's <code>sprintf</code> and <code>eval</code> functions along
with the {\tt input} command to write code that a user can modify as
+
with the <code>input</code> command to write code that a user can modify as
 
it runs.  This will allow you to write a single program to analyze
 
it runs.  This will allow you to write a single program to analyze
 
several parameter sets rather than having to write or copy several
 
several parameter sets rather than having to write or copy several
 
very similar pieces of code.
 
very similar pieces of code.
  
\subsection{The {\tt input} Command for Strings}
+
==The <code>input</code> Command for Strings==
As given in the Matlab help system, you can use the {\tt input}
+
As given in the MATLAB help system, you can use the <code>input</code>
command to obtain strings:
+
command to obtain strings<ref name="MATLAB Help">Quoted from MATLAB help file for <code>input</code></ref>
\begin{verbatim}
+
<source lang="text">
 
R = INPUT('What is your name','s') gives the prompt in the text
 
R = INPUT('What is your name','s') gives the prompt in the text
 
     string and waits for character string input.  The typed input
 
     string and waits for character string input.  The typed input
 
     is not evaluated; the characters are simply returned as a  
 
     is not evaluated; the characters are simply returned as a  
 
     MATLAB string.
 
     MATLAB string.
\end{verbatim}
+
</source>
 
This command allows you to type any valid combination of letters,
 
This command allows you to type any valid combination of letters,
numbers, and symbols.  You can therefore use {\tt input} to to obtain titles of
+
numbers, and symbols.  You can therefore use <code>input</code> to to obtain titles of
plots, file names, and other words which you may want to use later.
+
plots, file names, and other words or collections of characters which you may want to use later.
In order to have Matlab incorporate these words into commands,
+
In order to have MATLAB incorporate these words into commands,
however, you need to learn how to use {\tt sprintf} and {\tt eval}.
+
however, you need to learn how to use <code>sprintf</code> and <code>eval</code>.
  
\subsection{The {\tt sprintf} Command}
+
==The <code>sprintf</code> Command==
The {\tt sprintf} command works in nearly the same way as the {\tt
+
The <code>sprintf</code> command works in nearly the same way as the <code>fprintf</code>
  fprintf} command, only instead of sending characters to the screen
+
command, only instead of sending characters to the screen
  or to a file, {\tt sprintf} sends them into a Matlab variable.  For
+
or to a file, <code>sprintf</code> sends them into a MATLAB variable.  For
  example, in the code below, the {\tt input} command is used to
+
example, in the code below, the <code>input</code> command is used to
  generate a string ({\tt MyName}) and then the {\tt sprintf} command  
+
generate a string, called <code>MyName</code>, and then the <code>sprintf</code> command  
incorporates that string into a new string ({\tt MyGreeting}):
+
incorporates that string into a new string, called <code>MyGreeting</code>:
\lstset{basicstyle=\ttfamily}
+
<source lang="matlab">
\begin{lstlisting}[frame=single]
 
 
>> MyName = input('What is your name? ', 's');
 
>> MyName = input('What is your name? ', 's');
 
What is your name? Michael
 
What is your name? Michael
Line 37: Line 36:
 
MyGreeting =
 
MyGreeting =
 
Hi - my name is Michael
 
Hi - my name is Michael
\end{lstlisting}
+
</source>
 
 
 
You can use this technique if you want to tailor the title of a graph
 
You can use this technique if you want to tailor the title of a graph
 
by using specific values for that graph in the title.  For example, the  
 
by using specific values for that graph in the title.  For example, the  
code below produces the plot in Figure \ref{Strings:Title} by using
+
code below produces the plot below by using
 
numerical inputs both to determine the domain and function of the plot
 
numerical inputs both to determine the domain and function of the plot
 
and the title of the plot.  Note the use of the formatting commands in
 
and the title of the plot.  Note the use of the formatting commands in
the {\tt sprintf} function to make sure the proper number of decimal
+
the <code>sprintf</code> function to make sure the proper number of decimal
 
places appear - this will have to be adapted to each application.
 
places appear - this will have to be adapted to each application.
 
+
<source lang="matlab">
\begin{lstlisting}[frame=single]
 
 
n = input('Power to use: ');
 
n = input('Power to use: ');
 
x_min = input('Minimum value: ');
 
x_min = input('Minimum value: ');
Line 61: Line 58:
 
title(TheTitle)
 
title(TheTitle)
 
print -deps PlotSample.ps
 
print -deps PlotSample.ps
\end{lstlisting}
+
</source>
  
\begin{figure}[htb]
+
Note that the string for the title does not need to be created independently of the title command - the
\begin{center}
+
<source lang="matlab">
\epsfig{file=../GENERAL/MATLAB/PlotSample.ps, width=5in}
+
TheTitle = ...  
\caption{Plot demonstrating strings building the
+
    sprintf('Plot of y=x^{%0.1f} from %0.1f to %0.1f',...
  title\label{Strings:Title}}
+
    n, x_min, x_max);
\end{center}
+
title(TheTitle)
\end{figure}
+
</source>
 +
could be replaced with the simpler:
 +
<source lang="matlab">
 +
title(sprintf('Plot of y=x^{%0.1f} from %0.1f to %0.1f',...
 +
    n, x_min, x_max))
 +
</source>
 +
 
 +
If the code is run with the numbers 1.3, 0.1, 0.8, and 27 entered in that order, MATLAB produces the following plot:
 +
<center>
 +
[[Image:FlexiblePlotSample.png]]
 +
</center>
  
\subsection{The {\tt eval} Command}
+
==The <code>eval</code> Command==
 
In the above examples, strings and numbers could be used to change how
 
In the above examples, strings and numbers could be used to change how
 
particular lines of code work, but there was no way to make major
 
particular lines of code work, but there was no way to make major
 
changes to the code through input commands or strings.  For example,
 
changes to the code through input commands or strings.  For example,
 
there would have been no way to ask the user what color, point style,
 
there would have been no way to ask the user what color, point style,
and line style to use in the plot and have Matlab use that input in
+
and line style to use in the plot and have MATLAB use that input in
the {\tt plot} command.  It would be useful if the {\tt sprintf}
+
the <code>plot</code> command.  It would be useful if the <code>sprintf</code>
 
command could be used to build an entire line of code and then somehow
 
command could be used to build an entire line of code and then somehow
 
execute that line.
 
execute that line.
  
This is where the {\tt eval} function comes in.  The argument of the
+
This is where the <code>eval</code> function comes in.  The argument of the
{\tt eval} command is a string that Matlab executes as if it were
+
<code>eval</code> command is a string that MATLAB executes as if it were
 
typed on the command line.  For example, if you were to want the user
 
typed on the command line.  For example, if you were to want the user
to be able to enter two numbers and then tell Matlab what to do with
+
to be able to enter two numbers and then tell MATLAB what to do with
 
those (add, subtract, etc.), you could use the following code.  In
 
those (add, subtract, etc.), you could use the following code.  In
 
this case, the numbers entered were 1 and 6 and the operation was *.
 
this case, the numbers entered were 1 and 6 and the operation was *.
  
\begin{lstlisting}[frame=single]
+
<source lang="matlab">
 
>> Num1 = input('First number: ');
 
>> Num1 = input('First number: ');
 
First number: 1
 
First number: 1
Line 102: Line 109:
 
ans =
 
ans =
 
     6
 
     6
\end{lstlisting}
+
</source>
  
The use of the {\tt eval} command allows for much greater flexibility
+
The use of the <code>eval</code> command allows for much greater flexibility
in Matlab programming since you can have Matlab produce entire lines
+
in MATLAB programming since you can have MATLAB produce entire lines
 
of code for you.  Among the most useful places for this command is in
 
of code for you.  Among the most useful places for this command is in
 
generating plot names.  For example, the following code can be used
 
generating plot names.  For example, the following code can be used
 
whenever you want to specify the name of a plot to save during the
 
whenever you want to specify the name of a plot to save during the
 
execution of a program:
 
execution of a program:
\begin{lstlisting}[frame=single]
+
<source lang="matlab">
 
PlotTitle = input('Plot title: ', 's');
 
PlotTitle = input('Plot title: ', 's');
 
PlotCommand = sprintf('print -deps %s', PlotTitle)
 
PlotCommand = sprintf('print -deps %s', PlotTitle)
 
eval(PlotCommand)
 
eval(PlotCommand)
\end{lstlisting}
+
</source>
 +
 
 +
== More Examples ==
 +
=== Asking for and creating an arbitrary function ===
 +
With the <code>input</code> command, you can ask the user to input text; you can then <code>sprintf</code> this text as part of an anonymous function and <code>eval</code> that command to have MATLAB create the function.  That is:<source lang="matlab">
 +
MyFunction = input('Give me a function of x: ', 's')
 +
TheCommand = sprintf('f = @(x) %s', MyFunction)
 +
eval(TheCommand)
 +
</source>will as the user for a string, print the string along with the <code>f=@(x) ...</code> and then evaluate that line.  For example:<source lang="matlab">
 +
>> MyFunction = input('Give me a function of x: ', 's')
 +
Give me a function of x: x.^2
 +
 
 +
MyFunction =
 +
x.^2
 +
 
 +
>> TheCommand = sprintf('f = @(x) %s', MyFunction)
 +
 
 +
TheCommand =
 +
f = @(x) x.^2
 +
 
 +
>> eval(TheCommand)
 +
 
 +
f =
 +
    @(x)x.^2
 +
 
 +
 
 +
>> f([1 2 3 4])
 +
 
 +
ans =
 +
    1    4    9    16</source>
  
  
Line 121: Line 157:
  
 
== External Links ==
 
== External Links ==
 +
* [http://www.mathworks.com/access/helpdesk/help/techdoc/ref/input.html MATLAB Function Reference: input], The MathWorks
 +
* [http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sprintf.html MATLAB Function Reference: sprintf], The MathWorks
 +
* [http://www.mathworks.com/access/helpdesk/help/techdoc/ref/eval.html MATLAB Function Reference: eval], The MathWorks
  
 
== References ==
 
== References ==
Line 127: Line 166:
  
 
{{Protected Class Document}}
 
{{Protected Class Document}}
[[Category:EGR 53]]
+
[[Category:EGR 103]]

Latest revision as of 20:31, 8 June 2012

This page covers some ways MATLAB programs can be made more flexible by using strings. MATLAB's ability to use strings can come in very handy when writing programs to solve engineering problems. For some programs, you will want to use MATLAB's sprintf and eval functions along with the input command to write code that a user can modify as it runs. This will allow you to write a single program to analyze several parameter sets rather than having to write or copy several very similar pieces of code.

The input Command for Strings

As given in the MATLAB help system, you can use the input command to obtain strings[1]

R = INPUT('What is your name','s') gives the prompt in the text
    string and waits for character string input.  The typed input
    is not evaluated; the characters are simply returned as a 
    MATLAB string.

This command allows you to type any valid combination of letters, numbers, and symbols. You can therefore use input to to obtain titles of plots, file names, and other words or collections of characters which you may want to use later. In order to have MATLAB incorporate these words into commands, however, you need to learn how to use sprintf and eval.

The sprintf Command

The sprintf command works in nearly the same way as the fprintf command, only instead of sending characters to the screen or to a file, sprintf sends them into a MATLAB variable. For example, in the code below, the input command is used to generate a string, called MyName, and then the sprintf command incorporates that string into a new string, called MyGreeting:

>> MyName = input('What is your name? ', 's');
What is your name? Michael
>> MyGreeting = sprintf('Hi - my name is %s', MyName)
MyGreeting =
Hi - my name is Michael

You can use this technique if you want to tailor the title of a graph by using specific values for that graph in the title. For example, the code below produces the plot below by using numerical inputs both to determine the domain and function of the plot and the title of the plot. Note the use of the formatting commands in the sprintf function to make sure the proper number of decimal places appear - this will have to be adapted to each application.

n = input('Power to use: ');
x_min = input('Minimum value: ');
x_max = input('Maximum value: ');
points = input('Number of points: ');
x = linspace(x_min, x_max, points);
plot(x, x.^n, 'ko-');
xlabel('x (units)')
ylabel('y (units)')
TheTitle = ... 
    sprintf('Plot of y=x^{%0.1f} from %0.1f to %0.1f',...
    n, x_min, x_max);
title(TheTitle)
print -deps PlotSample.ps

Note that the string for the title does not need to be created independently of the title command - the

TheTitle = ... 
    sprintf('Plot of y=x^{%0.1f} from %0.1f to %0.1f',...
    n, x_min, x_max);
title(TheTitle)

could be replaced with the simpler:

title(sprintf('Plot of y=x^{%0.1f} from %0.1f to %0.1f',...
    n, x_min, x_max))

If the code is run with the numbers 1.3, 0.1, 0.8, and 27 entered in that order, MATLAB produces the following plot:

FlexiblePlotSample.png

The eval Command

In the above examples, strings and numbers could be used to change how particular lines of code work, but there was no way to make major changes to the code through input commands or strings. For example, there would have been no way to ask the user what color, point style, and line style to use in the plot and have MATLAB use that input in the plot command. It would be useful if the sprintf command could be used to build an entire line of code and then somehow execute that line.

This is where the eval function comes in. The argument of the eval command is a string that MATLAB executes as if it were typed on the command line. For example, if you were to want the user to be able to enter two numbers and then tell MATLAB what to do with those (add, subtract, etc.), you could use the following code. In this case, the numbers entered were 1 and 6 and the operation was *.

>> Num1 = input('First number: ');
First number: 1
>> Num2 = input('Second number: ');
Second number: 6
>> Operation = input('Operation: ', 's');
Operation: *
>> MyCommand=sprintf('%f %s %f',...
Num1, Operation, Num2)
MyCommand =
1.000000 * 6.000000
>> eval(MyCommand)
ans =
     6

The use of the eval command allows for much greater flexibility in MATLAB programming since you can have MATLAB produce entire lines of code for you. Among the most useful places for this command is in generating plot names. For example, the following code can be used whenever you want to specify the name of a plot to save during the execution of a program:

PlotTitle = input('Plot title: ', 's');
PlotCommand = sprintf('print -deps %s', PlotTitle)
eval(PlotCommand)

More Examples

Asking for and creating an arbitrary function

With the input command, you can ask the user to input text; you can then sprintf this text as part of an anonymous function and eval that command to have MATLAB create the function. That is:

MyFunction = input('Give me a function of x: ', 's')
TheCommand = sprintf('f = @(x) %s', MyFunction)
eval(TheCommand)

will as the user for a string, print the string along with the f=@(x) ... and then evaluate that line. For example:

>> MyFunction = input('Give me a function of x: ', 's')
Give me a function of x: x.^2

MyFunction =
x.^2

>> TheCommand = sprintf('f = @(x) %s', MyFunction)

TheCommand =
f = @(x) x.^2

>> eval(TheCommand)

f = 
    @(x)x.^2


>> f([1 2 3 4])

ans =
     1     4     9    16


Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References

  1. Quoted from MATLAB help file for input


Class Document Protection