Matlab - Getting start (779439), страница 11
Текст из файла (страница 11)
A cell array of empty matrices can be created with thecell function. But, more often, cell arrays are created by enclosing amiscellaneous collection of things in curly braces, {}. The curly braces are alsoused with subscripts to access the contents of various cells. For example,C = {A sum(A) prod(prod(A))}produces a 1-by-3 cell array. The three cells contain the magic square, the rowvector of column sums, and the product of all its elements. When C is displayed,you seeC =[4x4 double][1x4 double][20922789888000]This is because the first two cells are too large to print in this limited space, butthe third cell contains only a single number, 16!, so there is room to print it.5-95Programming with MATLABHere are two important points to remember. First, to retrieve the contents ofone of the cells, use subscripts in curly braces.
For example, C{1} retrieves themagic square and C{3} is 16!. Second, cell arrays contain copies of other arrays,not pointers to those arrays. If you subsequently change A, nothing happens toC.Three-dimensional arrays can be used to store a sequence of matrices of thesame size. Cell arrays can be used to store a sequence of matrices of differentsizes. For example,M = cell(8,1);for n = 1:8M{n} = magic(n);endMproduces a sequence of magic squares of different order.M =[[[[[[[[5-102x23x34x45x56x67x78x81]double]double]double]double]double]double]double]Other Data Structures236160675795554121351501617474620214342244026273736303133323435292838392541232244451918484915145253111056858595462631...641623135111089761241415181635743921421You can retrieve our old friend withM{4}Characters and TextEnter text into MATLAB using single quotes.
For example,s = 'Hello'The result is not the same kind of numeric matrix or array we have beendealing with up to now. It is a 1-by-5 character array.5-115Programming with MATLABInternally, the characters are stored as numbers, but not in floating-pointformat. The statementa = double(s)converts the character array to a numeric matrix containing floating-pointrepresentations of the ASCII codes for each character.
The result isa =72101108108111The statements = char(a)reverses the conversion.Converting numbers to characters makes it possible to investigate the variousfonts available on your computer. The printable characters in the basic ASCIIcharacter set are represented by the integers 32:127.
(The integers less than32 represent nonprintable control characters.) These integers are arranged inan appropriate 6-by-16 array withF = reshape(32:127,16,6)';The printable characters in the extended ASCII character set are representedby F+128.
When these integers are interpreted as characters, the resultdepends on the font currently being used. Type the statementschar(F)char(F+128)and then vary the font being used for the MATLAB Command Window. SelectPreferences from the File menu. Be sure to try the Symbol and Wingdingsfonts, if you have them on your computer. Here is one example of the kind ofoutput you might obtain.!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_‘abcdefghijklmnopqrstuvwxyz{|}~†°¢£§•¶ß®©™´¨¦ÆØ5-12Other Data Structures×±ðŠ¥µ¹²³¼½ªº¾æø¿¡¬ÐƒÝý«»…þÀÃÕŒœ-—“”‘’÷ÞÿŸ⁄¤‹›??‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔšÒÚÛÙ ˆ˜¯ °¸″ ÿConcatenation with square brackets joins text variables together into largerstrings.
The statementh = [s, ' world']joins the strings horizontally and producesh =Hello worldThe statementv = [s; 'world']joins the strings vertically and producesv =HelloworldNote that a blank has to be inserted before the 'w' in h and that both words inv have to have the same length. The resulting arrays are both character arrays;h is 1-by-11 and v is 2-by-5.To manipulate a body of text containing lines of different lengths, you have twochoices – a padded character array or a cell array of strings. The char functionaccepts any number of lines, adds blanks to each line to make them all thesame length, and forms a character array with each line in a separate row.
Forexample,S = char('A','rolling','stone','gathers','momentum.')produces a 5-by-9 character array.S =Arollingstonegathersmomentum.5-135Programming with MATLABThere are enough blanks in each of the first four rows of S to make all the rowsthe same length. Alternatively, you can store the text in a cell array. Forexample,C = {'A';'rolling';'stone';'gathers';'momentum.'}is a 5-by-1 cell array.C ='A''rolling''stone''gathers''momentum.'You can convert a padded character array to a cell array of strings withC = cellstr(S)and reverse the process withS = char(C)StructuresStructures are multidimensional MATLAB arrays with elements accessed bytextual field designators.
For example,S.name = 'Ed Plum';S.score = 83;S.grade = 'B+'creates a scalar structure with three fields.S =name: 'Ed Plum'score: 83grade: 'B+'Like everything else in MATLAB, structures are arrays, so you can insertadditional elements. In this case, each element of the array is a structure withseveral fields. The fields can be added one at a time,5-14Other Data StructuresS(2).name = 'Toni Miller';S(2).score = 91;S(2).grade = 'A-';or, an entire element can be added with a single statement.S(3) = struct('name','Jerry Garcia',...'score',70,'grade','C')Now the structure is large enough that only a summary is printed.S =1x3 struct array with fields:namescoregradeThere are several ways to reassemble the various fields into other MATLABarrays.
They are all based on the notation of a comma separated list. If you typeS.scoreit is the same as typingS(1).score, S(2).score, S(3).scoreThis is a comma separated list. Without any other punctuation, it is not veryuseful. It assigns the three scores, one at a time, to the default variable ans anddutifully prints out the result of each assignment. But when you enclose theexpression in square brackets,[S.score]it is the same as[S(1).score, S(2).score, S(3).score]which produces a numeric row vector containing all of the scores.ans =839170Similarly, typingS.name5-155Programming with MATLABjust assigns the names, one at time, to ans. But enclosing the expression incurly braces,{S.name}creates a 1-by-3 cell array containing the three names.ans ='Ed Plum''Toni Miller''Jerry Garcia'Andchar(S.name)calls the char function with three arguments to create a character array fromthe name fields,ans =Ed PlumToni MillerJerry Garcia5-16Scripts and FunctionsScripts and FunctionsMATLAB is a powerful programming language as well as an interactivecomputational environment.
Files that contain code in the MATLAB languageare called M-files. You create M-files using a text editor, then use them as youwould any other MATLAB function or command.There are two kinds of M-files:• Scripts, which do not accept input arguments or return output arguments.They operate on data in the workspace.• Functions, which can accept input arguments and return output arguments.Internal variables are local to the function.If you’re a new MATLAB programmer, just create the M-files that you want totry out in the current directory. As you develop more of your own M-files, youwill want to organize them into other directories and personal toolboxes thatyou can add to MATLAB’s search path.If you duplicate function names, MATLAB executes the one that occurs first inthe search path.To view the contents of an M-file, for example, myfunction.m, usetype myfunctionScriptsWhen you invoke a script, MATLAB simply executes the commands found inthe file.
Scripts can operate on existing data in the workspace, or they cancreate new data on which to operate. Although scripts do not return outputarguments, any variables that they create remain in the workspace, to be usedin subsequent computations. In addition, scripts can produce graphical outputusing functions like plot.For example, create a file called magicrank.m that contains these MATLABcommands.% Investigate the rank of magic squaresr = zeros(1,32);for n = 3:32r(n) = rank(magic(n));end5-175Programming with MATLABrbar(r)Typing the statementmagicrankcauses MATLAB to execute the commands, compute the rank of the first 30magic squares, and plot a bar graph of the result. After execution of the file iscomplete, the variables n and r remain in the workspace.3530252015105005101520253035FunctionsFunctions are M-files that can accept input arguments and return outputarguments. The name of the M-file and of the function should be the same.Functions operate on variables within their own workspace, separate from theworkspace you access at the MATLAB command prompt.A good example is provided by rank.