MATLAB:Flexible Programming

From PrattWiki
Revision as of 16:24, 9 July 2008 by DukeEgr93 (talk | contribs)
Jump to navigation Jump to search

\section{Using Strings} Matlab's ability to use strings can come in very handy when writing programs to solve engineering problems. For some assignments, you will want to use Matlab's {\tt sprintf} and {\tt eval} functions along with the {\tt 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.

\subsection{The {\tt input} Command for Strings} As given in the Matlab help system, you can use the {\tt input} command to obtain strings: \begin{verbatim} 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. \end{verbatim} 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 plots, file names, and other words 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 {\tt sprintf} and {\tt eval}.

\subsection{The {\tt sprintf} Command} The {\tt sprintf} command works in nearly the same way as the {\tt

 fprintf} command, only instead of sending characters to the screen
 or to a file, {\tt sprintf} sends them into a Matlab variable.  For
 example, in the code below, the {\tt input} command is used to
 generate a string ({\tt MyName}) and then the {\tt sprintf} command 

incorporates that string into a new string ({\tt MyGreeting}): \lstset{basicstyle=\ttfamily} \begin{lstlisting}[frame=single] >> 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 \end{lstlisting}

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 in Figure \ref{Strings:Title} 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 {\tt sprintf} function to make sure the proper number of decimal places appear - this will have to be adapted to each application.

\begin{lstlisting}[frame=single] 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 \end{lstlisting}

\begin{figure}[htb] \begin{center} \epsfig{file=../GENERAL/MATLAB/PlotSample.ps, width=5in} \caption{Plot demonstrating strings building the title\label{Strings:Title}} \end{center} \end{figure}

\subsection{The {\tt 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 {\tt plot} command. It would be useful if the {\tt sprintf} command could be used to build an entire line of code and then somehow execute that line.

This is where the {\tt eval} function comes in. The argument of the {\tt 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 *.

\begin{lstlisting}[frame=single] >> 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 \end{lstlisting}

The use of the {\tt 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: \begin{lstlisting}[frame=single] PlotTitle = input('Plot title: ', 's'); PlotCommand = sprintf('print -deps %s', PlotTitle) eval(PlotCommand) \end{lstlisting}


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


Class Document Protection