% >> help linspace % linspace Linearly spaced vector. % linspace(X1, X2) generates a row vector of 100 linearly % equally spaced points between X1 and X2. % % linspace(X1, X2, N) generates N points between X1 and X2. % For N = 1, linspace returns X2. % ................... %%
For example, we can try:
%
x = linspace(0,1,11)
%%
%
% Like our simple array x1,
% the vector x2 is a row vector. But the linspace has automatically filled the array with
% with 11 equally spaced entries
% between (and including) the values '0' and '1'.
%
% For larger arrays, we may wish to suppress the output to the screen. We
% do this by terminating our Matlab commands with a semi-colon
% (;).
% Try this
%
x = linspace(0,1,1001);
%%
%
% The first few entries in x3 are
%
[x(1) x(2) x(3) x(4)]
%%
%
% We will talk more about indexing arrays in a later lab. For now,
% we can look at each of these three variables in memory to see that they are the
% expected lengths.
%
whos
%%
%
% The variable ans is also included in
% the above list. This is the default variable name used anytime you do
% not explicitly provide a variable name. In our case, we did not
% explicitly provide a variable name for the list of the first four entries
% of x3.
%
%% Arithmetic operations involving arrays
%
% We can include arrays in arithmetic operations almost as easily as we can
% compute using scalar variables. Again, we will set up a vector containing
% equally spaced points
%
x = linspace(0,1,11)
%%
%
% and now
%
y = 2*x
%%
%
% This simple command produced a variable y whose entries
% are twice that of all the corresponding entries in x.
% Here are a few more examples.
%
z = cos(pi*x)
%%
w = log(exp(3*x + 1))
%%
u = x + y - 4*z
%% Element-wise operations using "dot" operators
%
% You may have noticed that in the above examples, we did not include any
% expressions involving the multiplication or division of arrays with each
% other. The reason for this is that whereas addition and substraction and
% elementary function evaluation are all well defined mathematical meanings
% when applied to arrays, the operations like x*x
% are ambiguous. Do we mean a scalar product? Or a matrix multiply in the
% linear algebra sense? Or something else?
%
%
For plotting purposes, the correct answer is "something
% else". Suppose we wanted to construct a vector y
% who entries contained the square of each entry of
% x. If we try
%
%
% >> y = x*x %%
we get the error
%% Error using *
% Inner matrix dimensions must agree.
%
% % In fact, we can also get errors using the / % or the ^ operators, as the following example % illustrate. %
% >> 1/x %%
% Error using /
% Matrix dimensions must agree.
%
% % >> y = x^2 %%
% Error using ^
% Inputs must be a scalar and a square matrix.
% To compute elementwise POWER, use POWER (.^) instead.
%
%
%%
%
% The problem is that Matlab is expecting that dimensions of our matrices
% agree in some linear algebra sense. But what we want is to apply our
% operation to each element of the array. To use Matlab terminology, we
% want an element-wise operation. We do this in Matlab by putting
% a "dot" in front of our multiplcation, division or exponentiation
% operators. The resulting "dot" operators are '.*', ./ or '.^'. For example, either one of the following
% expressions will give us our desired vector y.
%
y = x.*x
%%
y = x.^2
%%
%
% We can now take the element-wise inverse of each entry of x:
%
y = 1./x
%%
%
% Using exponentiation with dot operator will also work in this case
%
y = x.^(-1)
%%
%
% You notice that the first entry is the special value Inf, which results when we divide by 0.
% We can now extend our use of the dot operator to more complicated % expressions. In each of the following examples, we wish to evaluate the % given expression at an array of values x where x is defined as % x = linspace(0,1,11) %% % %
Example 1
%
% $$y = \cos(\pi x)\sin(\pi x)$$
% where the variable $x$ is an array.
%
%
y = cos(pi*x).*sin(pi*x)
%%
%
%
Example 2
%
% $$y = \frac{\sin(\pi x)}{\cos(\pi x)+2}$$
%
%
%
y = sin(pi*x)./(cos(pi*x)+2)
%%
%
%
Example 3
%
% $$y = 2^{10 x}$$
%
%
%
y = 2.^(10*x)
%%
%
%
Example 4
%
% $$y = \exp(-10(x-1)^2)^{-1}$$
%
%
%
y = exp(-10*(x-1).^2).^(-1)
%%
%
% or
%
y = 1./exp(-10*(x-1).^2)
%% Plotting curves
%
%
Matlab has an extremely powerful set of tools for plotting
% functions in one, two and three dimensions. We will explore some very
% basic one-dimensional plotting commands here.
%
% Suppose we want to graph the function
%
% $$ f(x) = \cos(2 \pi x) $$
%
%
First, construct an array x (our domain) over % which to compute the function values y. Then % evaluate y. % x = linspace(-2,2,101); %%% y = cos(2*pi*x); %% % % Don't forget to use the semi-colon, or you will print all 101 values to % the screen. To create a plot of y verses y, use the Matlab plot % command : % plot(x,y) %% % % The plot brings up a new window, called a % figure windown. Near the top of the window, you should see a % number associated with this window. This is our first plot, so the % figure number is '1'. % %% Axis limits % % To determine axis limits, Matlab uses the minimum and maximum of your % x and y values. In our % current example, our x values were in the range $x \in [-2,2]$ and our y were in the range $x \in % [-1,1]$. We can change this viewing "window", or axes limits using % the axis command. %
% >> help axis % axis Control axis scaling and appearance. % axis([XMIN XMAX YMIN YMAX]) sets scaling for the x- and y-axes % on the current plot. % .................... %%
This command takes an array argument defined using the square brackets
% [].
% To adjust the limits on our current figure window, to region $[-1, 1]\times [-2, 2]$. we can use
%
axis([-1 1 -2 2])
%%
%
% You can set the axis limits for each axis separately using the commands
% xlim and ylim.
% For example,
%
xlim([-2 2])
%%%
ylim([-1 1])
%%
%
% restores the axis to their original settings.
%
% To retrieve these values from the current figure window, we can query the
% graphics handle gca :
%
get(gca,'xlim')
%%
get(gca,'ylim')
%%
%
% You may also want to preserve the aspect ratio of the plot, so that
% visually, 1 unit of distance on the x-axis is the same as 1-unit on the
% y-axis. The command
%
daspect([1 1 1])
%%
%
% is one way to do this. The first two arguments indicate the relative
% ratio of the x and y axis. The third argument is for the z-axis, and
% can be always set to 1 for present purposes.
%
%% Adding additional plots to an existing window
%
% Very often, we wish to add additional curves to existing plots. This
% be easily done with the hold command.
% First, we will clear the current figure window, re-draw our previous
% plot, "hold" the state of the first plot, and then add a second plot.
%
clf
%%%
plot(x,y)
%%%
hold on
%%%
plot(2*x,y/2)
%%
%
% To plot a curve in red instead of the default blue, add a color
% attribute to the plot command :
%
plot(2*x,y/2,'r')
%%
%
% Also available are different line types, e.g. dashed lines, dotted
% lines, and so on. To use these, you can augment the color command
% with a line style. For example, to get a dashed line, use
% the '--' line attribute. Using an
% additional argument in this string, we can specify both the color and
% the line type :
%
plot(4*x,y/4,'k--')
%% Adding symbols to the plot
%
% We can add symbols to the plot as well. Suppose we want to put a
% symbols at each maximum value and minimum value of our last plot, which
% was a graph of the function
% $g(x) = f(4x)/4 = \cos(4 \pi x)/4$.
% This function has zeros whenever $g'(x) =
% 0$, or when
% $$x_{minmax} = [-1.5, -1, -0.5, 0, 0.5, 1, 1.5]$$
% so we will create a simple array to store these values:
%
xminmax = [-1.5, -1, -0.5, 0, 0.5, 1, 1.5];
%%
%
% We can now plot a symbol at each $(x,y)$
%
plot(4*xminmax, cos(2*pi*xminmax)/4,'k*')
%%
%
% You can experiment with different colors, line styles, and symbols by getting
% help on the plot command. For example,
% some common colors, styles and symbols are
%
%
% >> help plot % ........................ % Various line types, plot symbols and colors may be obtained with % plot(X,Y,S) where S is a character string made from one element % from any or all the following 3 columns: % % b blue . point - solid % g green o circle : dotted % r red x x-mark -. dashdot % c cyan + plus -- dashed % m magenta * star (none) no line % y yellow s square % k black d diamond % w white v triangle (down) % ^ triangle (up) % < triangle (left) % > triangle (right) % p pentagram % h hexagram % ...................... %% %% Adding a title and axis labels % % A plot is not complete without a title, and axes labels. Use the % following commands to add these items to your plot. % xlabel('x') %%% ylabel('y') %%% title('A simple plot') %% % % You can change the font-size (among other things) by passing additional % arguments to the xlabel, % ylabel and % title commands: % xlabel('x','fontsize',18) %%% ylabel('f(x)','fontsize',18) %%% set(gca,'fontsize',18) %%% title('A simple function','fontsize',18,'fontweight','bold') %% Printing the figure window % % Eventually, you will want to print you plot for use in other documents, % such as Word, Latex, or a webpage. You can produce an image file in any % number of formats. A format that works well for most purposes is the % % PNG (Portable Graphics Format). To print out your figure using this % format, use the print command: % print -dpng simple_function.png %% % % A list of available formats can be found by looking at help on % print command. %
% >> help print % print Print figure or model. Save to disk as image or MATLAB file. % ...................... % print -device -options filename % If you specify a filename, MATLAB directs output to a file instead of % a printer. print adds the appropriate file extension if you do not % specify one. % ..................... % Built-in MATLAB Drivers: % ..................... % -depsc2 % Encapsulated Level 2 Color PostScript % ..................... % -djpeg%% JPEG image, quality level of nn (figures only) % E.g., -djpeg90 gives a quality level of 90. % Quality level defaults to 75 if nn is omitted. % ..................... % -dtiff % TIFF with packbits (lossless run-length encoding) % compression (figures only) % ..................... % -dpng % Portable Network Graphic 24-bit truecolor image % (figures only) %
Many of the commands discussed above for adding titles and so on to % your plots can be done from menu items in the figure % window. These are handy if you plan to make a plot only % once. But often, you will run a simulation several times, % and would like all of your plot attributes to be added automatically. % For this reason, we have discussed mainly the command line % methods for modifying plots. % %% Clearing and closing graphics windows % % To clear the graphics window you can use the clf command, which stands for "clear figure". % This only removes any plotting elements from the current figure window % but does not close the window itself. %
% >> clf %%
To close out a figure window % can use the close command. %
% >> close all %%
You can selectively close figure windows by supplying an argument to % the close command: %
% >> close(1) %% %% The EZ way to plot % % The easiest way to plot a function using Matlab is to use the ezplot command. At its simplest, this command % requires a single argument, the function handle. % close all; %% f = @(x) exp(cos(x)).*sin(x); %% ezplot(f); %% % % By default, ezplots plots over the range $[-2\pi, 2\pi]$. To specify a custom range over % which to plot the function, pass in two additional arguments, the left % and right endpoints of the range in an two element array. % a = -pi/2; %% b = 3*pi/2; %% ezplot(f,[a b]); %% % % Using ezplot, you can still add titles and axes % labels to your plots as before. In fact, it is possible to change most % aspects of the plot, such as the line type and color, using what is known % as "Handle Graphics". %
Compare your answers with the solutions.
%