MATLAB:Flexible Programming

From PrattWiki
Jump to: navigation, search

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