Sie sind auf Seite 1von 5

MATLAB Handout: General Tips and Commands

The following sets of commands make life easier with MATLAB.

Configuring MATLABs Display


These commands allow the user to specify how MATLAB displays data. clc format compact format long g warning off / on fprintf(string) Clear screen MATLAB displays output on every line (type help format for more information) Displays best 15 digits for fixed and floating point numbers (type help format for more info) Suppresses / displays all subsequent warning messages Display messages to the screen, formatted as in C (see fprintf in the file IO section)

Memory Management Commands


MATLAB handles its own memory allocation / deallocation, but it may not be smart about it. To speed up processes, it may be helpful to control some of MATLABs allocation / deallocation routines yourself, especially when handling large amounts of data. Allocating Memory for Large Vectors and Arrays Allocate an array of size n1 x n2 x n3 x and set all elements to zeros(n1,n2,n3,) be zero. Allocate an array of size n1 x n2 x n3 x and set all elements to ones(n1,n2,n3,) be one. Allocate an array of size n x m (limited to 2D) and set all elements to eye(n,m) be zero except those on the primary diagonal, which are set to one. (Identity Matrix) Deallocating Memory Clears the variables x, y, and z from memory this will clear up clear x y z space that later variables can use. It may speed things up. clear all Clears all memory A very useful example of user-defined allocation that speeds up the construction of a vector (or array): Slow Faster >> x = zeros(N,1); >> for i=1:N >> for i=1:N >> x(i) = foo; >> x(i) = foo; >> end >> end The reason this is faster is because MATLAB knows how big x is from the start and just fills it in, whereas in the slow case, MATLAB has to re-allocate a larger array every time you increase i in the for loop.

Plotting
figure figure(x) plot plot3 semilogx semilogy loglog polar surf / mesh contour hold on / off axis([x1 x2 y1 y2]) axis equal title(string) xlabel, ylabel, zlabel legend text grid subplot axes close close all Create a new figure Create the figure x, or make figure x active 2-dimensional plotting routine (type help plot for more info) 3-dimensional plotting routine 2D plotting with logarithmic x-axis 2D plotting with logarithmic y-axis 2D plotting with logarithmic x and y-axes Plot in polar coordinates Create a surface / mesh Create a contour plot Allow more plots to be added to the same axes Set the axes Make the axes equal in height/width (type help axis) Set the title of a figure Set the x, y, and z labels Add a legend to a figure Add text to the plot Add a grid to the plot Place multiple plots in the same figure (type help subplot) Creates a new plotting axis in the figure (type help axes) Closes the current figure, i.e., close(gcf) Close all figures

A few other things: >> plot(x,y,'r','linewidth',2) will make a red line of thickness 2 >> plot(x,y,'m--','linewidth',5) will make a magenta dashed line of thickness 5 >> plot(x,y,'g.','markersize',10) will make a set of green dots of size 10 >> plot(x,y,'k*','markersize',10) will make a set of black stars of size 10 Type help plot for more information

Handles
All figures, axes, structures, etc have handles associated with them. They are similar to pointers in other languages. The user may display any property of an object by looking at the right handle; the user may also set any property in an object by setting the right property of the corresponding handle. Here are some examples: figure(10) Create a new figure with the handle 10 gcf Get the current figures handle (10) get(10) Displays lots of properties about that figure! x = rand(10,1); Produce random vectors for x and y y = rand(10,1); h1 = plot(x,y) h1 is the handle of the plotted line get(h1) Display all of the properties of the line set(h1,Color,[.2,.7,1]) Set the color of the line to teal gca Get the current axis information set(gca,YScale,Log) Set the current y-axis to be logarithmic set(gca,XAxisLocation,top) Move the x-axis labels to the top MATLAB allows the user to do pretty much anything that is desired. Its a lot of work, but it can be rewarding.

Input/Output
The user may write to and read from files. The following commands are useful; type help <command> for more information about these. fopen fclose fread fwrite fscanf fprintf save load frewind diary input keyboard Open a file for reading or writing Close the file (anything written doesnt actually get written until you do this!) Read binary data from a file Write binary data to a file Read formatted data from a file Write formatted data to a file Save workspace variables to disk Load workspace variables from disk Rewind the file Save text of MATLAB session Prompt for user input Invoke keyboard from M-file

Vectors and Arrays


MATLAB has been optimized to perform operations on vectors and arrays. If at all possible, the user should invoke vector/array math rather than invoking for/while loops. It will save vast amounts of time. length size / ndims isempty * / ^ .* ./ .^ reshape inv cond .' or ' min, max sum, prod mean, median, std, diff, cov hist, histfit norm dot, cross find sort cat angle unwrap Determine the number of elements in a vector Determine the size / number of dimensions of a matrix Determine if a vector or matrix is empty Matrix multiplication, division, power, etc Element-wise multiplication, division, power, etc (Type help . or help slash for more information. DO IT, its interesting!) Reshape an array Matrix inversion Condition number of a matrix Transpose or complex conjugate transpose Finds the minimum / maximum in a vector or column of an array Vector-sum, vector-product Statistical mean, median, standard deviation, difference, covariance Place the elements in a vector into a histogram / add the fitted curve. Find various types of norms on a 3-vector or array Dot-product, cross-product Perform a search on the elements in a vector or array Sort the elements in a vector or array Concatenate vectors / arrays Determine the phase angle of a complex array Unwrap the phase angle

The find command (among others) requires logical operators, including the following: == or eq() Test equality ~= or ne() Not equal < or lt() Less than

> or <= or >= or & or | or ~ or xor() any() all()

gt() le() ge() and() or() not()

Greater than Less than or equal to Greater than or equal to Logical AND Logical OR Logical NOT Logical XOR (Exclusive OR) True if any element is nonzero True if all elements are nonzero

Random Numbers
rand rand('state',sum(100*clock)) randn Uniformly distributed random number generator Ensure a new seed each time Normally-distributed random number generator

Functions / Scripts
New functions may be added to MATLAB's vocabulary if they are expressed in terms of other existing functions. The commands and functions that comprise the new function must be put in a file whose name defines the name of the new function, with a filename extension of '.m'. At the top of the file must be a line that contains the syntax definition for the new function. For example, the existence of a file on disk called STAT.M with: function [mean,stdev] = stat(x) %STAT Interesting statistics. n = length(x); mean = sum(x) / n; stdev = sqrt(sum((x - mean).^2)/n); defines a new function called STAT that calculates the mean and standard deviation of a vector. The variables within the body of the function are all local variables. Type help function for more information about functions and subfunctions. Other function commands: return varargin / varargout nargin / nargout inputname mfilename Force an early return from a function Variable length input/output argument list Number of function input/output arguments Input argument name Name of currently executing M-file

A SCRIPT file is an external file that contains a sequence of MATLAB statements. By typing the filename, subsequent MATLAB input is obtained from the file. SCRIPT files have a filename extension of ".m" and are often called "M-files". Variables contained in the script are external variables; variables declared in the script are usable outside of the script. Function calls tend to take less time during compilation because they are only compiled once, whereas scripts are compiled each and every time they are called. Thus, functions tend to be faster if called numerous times.

One other note: The user can evaluate a string as a function/script call by using the eval command. The sprintf command helps to convert formatted text to a string.

Structures
MATLAB, like many other languages, has the capability to construct user-defined structures. struct . isfield fieldnames getfield setfield rmfield deal Create a structure, or convert an object to a structure Access a structure field Determine if a field is in a structure Get structure field names Get structure field contents Set structure field contents Remove structure field Deal inputs to outputs (assign several elements simultaneously)

Miscellaneous
global tic / toc clock abs sign round, ceil, floor, fix mod / rem i / j ! who whos what which lookfor lookfor -all exist Declare global variables Computes the amount of time required to perform some operations Current date and time Absolute value The (+/-) sign of a variable Round a number in various ways Modulus / remainder Imaginary units, sqrt(-1) System Call List current variables List current variables, long form List functions in a given directory Finds the directory containing a given function or file Finds all functions in all directories in the path that might have something to do with a given key word Searches harder Checks to see if variables or functions are defined

Das könnte Ihnen auch gefallen