You are on page 1of 5

MATLAB for the Faint Hearted

help * why % A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16] A = {hello; 5; [1X2]}; sum(A) A sum(A) diag(A) sum(diag(A)) fliplr(A) A(i,j) A(k) A(8) X=A; X(4,5)=17 Gets help information for * function Provides succinct answer to almost any question. Comments lines out of a function (Lines appear but MATLAB does run them) defines a 4x4 matrix by rows of data separated by ; defines a matrix where rows can be unequal length and different types CELLSTR sums each row produces the transpose produces a column vector containing the row sums produces the elements on the main diagonal (upper left to lower right) produces the sum of the elements on the main diagonal flips a matrix from left to right (to get anti-diagonal) specifies element in row i, column j of matrix A refers to the elements of a matrix with a single subscript k is the same as A(4,2) for a 4x4 matrix A if you store a value in an element outside of the matrix, the size increases to accommodate the newcomer: 1 2 3 4 0 5 6 7 8 0 9 10 11 12 0 13 14 15 16 17 row vector containing integers 1 to 10: 1 2 3 4 5 6 7 8 9 10 specifies increment for spacing: 100 93 86 79 72 65 58 51 0 0.7854 1.5708 2.3562 3.14156 creates a list of 37 equally spaced numbers from 0 to 100 refers to the first k (e.g., 1 to k) elements of the jth column of A computes the sum of the fourth column colon by itself refers to all the elements in a row or column and the keyword end refers to the last row or column; this will compute the sum of the elements in the last column of A makes a magic square out of almost any size matrix for each of the rows of matrix B, reorder the elements in the order 1, 3, 2, 4 MATLAB does not require any type declarations or dimension statements; this creates a 1x1 matrix and stores the value 25 as its single element creates a 2x4 matrix of all 0s creates a 2x4 matrix of all 1s creates a 2x4 matrix of uniformly distributed random elements creates a 2x4 matrix of normally distributed random elements creates a 3x3 matrix of all 5s Concatenation: from A, a 4x4 matrix, make B, a 8x8 matrix by adding on 3 submatrices deletes the second column of X ; at the end of the command suppresses output (e.g., for when you dont want to display large amts of info like matrices) when not enough room on line, use three periods followed by Return to indicate that the statement continues on next line format command controls display, not computation or saving, for example, 4/3 ratio display 1.3333

1:10 100:-7:50 0:pi/4:pi linespace(0,100,37) A(l:k,j) sum(A(1:4,4)) sum(A(:, end)) B = magic(4) A=B(:,[1 3 2 4]) num_students = 25 Z=zeros(2,4) Z=ones(2,4) Z=rand(2,4) Z=randn(2,4) F=5*ones(3,3) B=[A A+1;A+2 A+3] X=A;X(:,2)=[ ] A=magic(100);

format format short

format short e format short g format long format long e format long g format bank format rat format hex format compact sprintf

1.3333e+000 1.3333 1.33333333333333 1.33333333333333e+000 1.33333333333333 1.33 4/3 4/3 Suppresses many of the blank lines that appear in the output write formatted data to string

Graphics
plot(y) plot(x,y) plot(x,y,color_style_marker) graph of y vs. x; can also plot multiple curves on the same plot graph of y vs. x; can also plot multiple curves on the same plot specifies color, line style, and markers (e.g., plus signs of circles) see advanced graphics specifies a yellow dotted line and places plus signs at each data pt opens a new figure window and make it the current figure makes an existing figure window the current figure where n is the number in the figure title bar allows the addition of plots to an existing graph; adds new data to the current graph, rescaling if necessary displays multiple plots in the same window or print them on the same piece of paper. Breaks the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot adds label on x-axis adds label on y-axis adds label on z-axis adds title inserts text at (x,y) location in figure brings up all the attributes of figure n Get handle to current axis Clear current axis

plot(x,y,y:+) figure figure(n) hold on subplot(m,n,p) xlabel(freq) ylabel(age) zlabel(gender) title(title) text(x,y,text) get(n) gca cla

Saving
save filename path ls dir cd diary filename diary off save X X outfile = [cd '\data\sub' num2str(sub) 'day' 'data.dat']; fid = fopen([outfile],'w'); data(trial,:) = [trial stimuli(trial,:) response1 rt1]; fprintf(fid,'%3i %i %i %1.4f saves the entire workspace as filename.mat in binary format easily read by MATLAB shows the search path List files in current directory List files in current directory Current dictionary creates a diary of your MATLAB session in a diskfile stops recording the session Save matrix X to current directory Create file name Create file Line of data for file Write formatted data to file

\n',data(trial,:)' ); fclose(fid); load magik.dat type * edit * home clc pause pause(n) ifend if isequal(A,B) if isempty ifall ifany Switchcaseend

Close file reads the file and creates a variable magik containing the matrix; the load command reads the binary file(s) generated by earlier MATLAB sessions, or reads text files containing numeric data (not necessarily from MATLAB). Gets text of * and prints it in the command window Opens * Moves cursor to upper left corner of command window Clears command window Waits for any key press to continue Waits n seconds before continuing optional elseif and else keywords checking for equality between two variables checks to see if matrix is empty switch statement executes groups of statements based on the value of a variable or expression. Unlike C, if the first case is true, no other cases are executed: switch(A+B) case 0 statements case 1 statements end Does the variable/file exist Copy the matrix M to the clipboard in tab delimited format

exists(data) Copytext(data)

Operators (aka doing mathy stuff)


help elfun help specfun help elmat Arithmetic operators plus uplus minus uminus mtimes times mpower power mldivide mrdivide ldivide rdivide kron sqrt exponential Relational operators eq ne lt gt le ge list of elementary mathematical functions, including: +, -, *, /, \ (left division), ^ (power), (complex conjugate transpose), ( ) (specify evaluation order), sqrt, sin. Some are built-in, some are in M-files (e.g., gamma, sinh) list of more advanced mathematical and matrix functions list of more advanced mathematical and matrix functions - Plus - Unary plus - Minus - Unary minus - Matrix multiply - Array multiply - Matrix power - Array power - Backslash or left matrix divide - Slash or right matrix divide - Left array divide - Right array divide - Kronecker tensor product - Square root -exponential of the elements of X, e to the X. - Equal - Not equal - Less than - Greater than - Less than or equal - Greater than or equal == ~= < > <= >= + + * .* ^ .^ \ / .\ ./ kron sqrt() exp(x)

Plotting (aka making things look pretty)


plot(X,Y,S), where S is a character string made from one element from any or all the following: b g r c m y k v ^ < > p h blue green red cyan magenta yellow black triangle (down) triangle (up) triangle (left) triangle (right) pentagram hexagram . o x + * s d point circle x-mark plus star square diamond - solid : dotted -. dashdot -- dashed

For example, plot(X,Y,'c+:') plots a cyan dotted line with a plus at each data point plot(X,Y,'bd') plots blue diamond at each data point but does not draw any line.

Keyboard Shortcuts

Actions
comment uncomment execute save close quit command window break indent indent find find again new file delete file cut copy past

Mac
+y +u +e +s +w +q +0 +. +[ +] +f +g +n delete +x +c +v

PC
ctrl+r ctrl+t F5 ctrl+s crtl+w ctrl+q ctrl+c ctrl+[ ctrl+] ctrl+f F3 Delete ctrl+x ctrl+c ctrl+v

This is a work in progress. Please any comments, suggestions, or additions to Brian Spiering, bspiering@gmail.com

You might also like