Matlab
What is the normal procedure for creating GUIs programmatically
Create the parent figure window and make it invisible -then all UI obj. added to it and properties are set -now the GUI is made visible
-blanks(n)
Creates a string of n blank characters -can be used between words to appropriately concatenate strings --Transposing creates new lines, similar to '\n' function
-length(vec)
returns the number of elements in vec
what does UI stand for?
user interface
What is a control character?
Characters that cannot be printed but accomplish a task (backspace or tab)
String definition
Consists of any number of characters and is contained in single quotes -Is actually a vector in which every element is a single character
What is a vector of nested structures
Combining vectors and nested structures -vectors of structures in which some fields are structures themselves
-Cellstr(characterarray)
Converts character array with blanks to cell array without
What is the parent of any GUI?
Figure window
How are complex numbers added and subtracted
For the two complex numbers; z1 = a+bi z2 = c + di z1 + z2 == (a+c) + (b+d)i z1 - z2 == (a-c) + (b-d)i
Why won't data that isn't a matrix work with the load and save command
If data to be written or file to be loaded is in a different format, Lower level input/output functions are needed
What is one method for finding the inverse for a two x two matrix?
Involves calc.determinent D
What does GUIDE allow for?
It allows users to graphically lay out GUI and MATLAB generates the code for it automatically
How is binary search accomplished
It assumes a sorted vector and searches more quickly
What is MATLAB Program Organization?
It consists of a script that calls the functions to do the actual work
what is uibuttongroup
It is a means of grouping together buttons
What is a persistent variable
It is an abnormal variable that is not cleared when a function is finished being executed -To make a variable consistent, one needs to declare it before execution
How does one create a cell array?
Some syntax is the same as with vectors and matrices -values within rows separated by ' ' or , and rows by ; -{} used instead of [] -pre-allocate the size of a cell array using -cell(r,c)
What are selection and branching statements?
Statements in code that choose whether to execute statements or not, and help us choose amongst or between statements
Cell Array
Stores values of different types and can be looped -vectors or matrices with values referred to as elements -common use to store strings of different lengths
How will vectors having set operator function run on them be displayed?
They will be sorted in ascending order -to stop this -issorted() or -ismember()
What does a conditional loop do
iterates until a certain criterion is met
-zlabel()
labels the z axis
-comet()
leads through data points of a plot 1 by 1, leaving a trail in the wake
what does the help function command do
lists the comments associated with that function
without a built in function, how would the mean of a data set be found
looping through a vector and summing each index and dividing by length
-expand()
multiply out terms
-jet(arg)
number of desired colors can be specified here
What are the three types of variables in Matlab?
numbers (integers and floats), characters (strings and letters, and logical(True or False)
What are GUIs an example of?
object oriented programming -Parent would be figure window and children would be graphic objects --Parent user interface object can be a figure, UIpanel or UIbuttongroup
What do all figures consist of?
objects, each of which is assigned an object handle
-cellplot(cellarray)
puts graphic display in the figure window -not the contents, just the name of the cells and content
Rectangle -> Polar Coordinates
r and theta r = |z| theta = arctan(b/a) a = rcos(theta) b = rsin(theta)
What is the range of curvature for the rectangle object?
ranges from [0,0] (rectangle) to [1,1] (ellipse)
-fscanf()
reads files into a matrix using conversion formats (%s) -lower level function
-rmfield(package, field)
removes a field from a structure -not a permanent change unless stored under original structure
strrep()
replace all occurrences of one substring with another within a longer string -strrep(string, oldsubstring, newsubstring)
-all()
returns 1 if all elements are true and 0 if any elements are false
abs()
returns the absolute value
How do you save workspace
save 'filename'
How do you display the contents of an anonymous function?
type its function handle
How can GUI parents be specified
uicontrol(parent, ...)
How can you sort a cell array?
use -sort(cell array)
How do we sort a string alphabetically?
use -sortrows()
How do we count how many times a while loop is activated?
use a counter variable set to 0 before the loop
How do we error check with a while loop?
use while input condition ~met input condition = input('invalid, enter a valid input: ')
-fprintf('string with placeholders', placeholder variable)
used for formatted output statements in string form
-patch()
used to create a patch graphic of 2D polygons -ex. x = [0, 1, 0.5]; y = [0, 0, 1] patch(x,y,'r')
type command
used to see the contents of a script
How does MATLAB display images
uses rep of matrix with each element corresponding to a pixel, with each element storing the color of said pixel
-struct()
uses the name of fields as arguments which are strings immediately followed by the value of that field.
How are most UI objects created
using the uicontrol() function
-eye()
will create and identify matrix of nxn
disp(complex number)
will display both components of a real and imaginary number
-colormap()
will display default colormap named 'jet'
-Echo(on/off)
will display every statement and result as executed
-pretty()
will display symbolic expressions as exponents
-feval(functionhandle, value)
will evaluate and run handle on value
-fprintf(complex number)
will only display the complex number unless otherwise specified
isreal complex number
will only return logical 1 if there is no imaginary component of a number
-find()
will return an index in an array that meets a criterior
-fieldnames(package)
will return the names of fields that are in a structure -The fields vary in length, so it will return a cell array
-numdun()
will return the numerator and denominator seperately
dot operator use in structures
Alternative method uses the . operator to refer to fields and then assign a value to that field ex. structure.field=values -Using this for structure creation is generally inefficient, but using this to alter existing structures into new structures with common values can be useful
Common operators in Matlab
+ addition - subtraction and negation * multiplication / divided by \ divided into ^ or e exponentiation sqrt square root
What are the line symbols and their descriptions
-- dashed -. dash dotted : dotted - solid
What are the requirements for making a matrix
-Rows must always have an equal number of values
Notes on memory of data types
-The value following 'int' represents the number of bits used to store the value (int64, int32, etc....)
format commands
-format short - changes decimals to 4 places (default) -format long - changes decimals to 15 places -format loose - lines between data entry for viewing -format compact - reduces lines between data for view
Random number functions
-rand( , ) returns a random number ranging from 0 to 1 -rng( ) sets initial seed (used to generate random num) -randn( ) generates norm distr of random numbers -randi([n,n]) returns a random integer in range n to n
How can rand and randi be used to make matrices of random nums
-rand(2) makes 2x2 -rand(1,3) makes 1 row x 3 col -randi([low, high], 2) makes 2x2 in low-high range randi nonsquare same as nonsquare rand syntax
What are the steps to developing an algorithm
1. Define where the input came from -could be external file or direct input from keyboard 2. Input steps prompting and reading into program 3. Determine the form of output -can go to an external file or output device --try not to print the output only, be descriptive
Logrithms functions and syntax in MATLAB
A logrithm for which x = b^y is y = logb(x) -frequently used bases of logrithms include 10, 2, and e -log(x) returns e, log2(x) returns base 2, log10(x) base 10
What is a compiler
A program that translates high level languages into an executable file -The original file is called the 'source code' -resulting executable file is called 'object code'
Computer programming definition
A sequence of instructions in a given language that accomplishes a task. computers follow these instructions sequentially
What is a vector index?
A sequential numbering of elements -in matlab you can call an element with vectorname(element) -you can also change a value of a stored vector with vec(element #) = new element # -- This process can also be used to extend vectors with elements in place
-reshape(mat)
Changes the dimensions to divisible dimensions columnwise -the original matrix is maintained while the reshape is stored in ans
How can I generate a random real float in a specified range?
First create variables low and high Then use the expression rand*(high-low) + low
who command
Function that shows variables that have been defined in the Command Window
Simplified algorithm steps
Get input -> Calc result -> display the output
What is an Interpreter
Goes through code line by line translating and executing as it goes
What is a block comment?
It is used to describe a script or function in a script
what does the slice (colon) operator do?
It is used to iterate values between two integers or denote a step value for a vector e.g. vec = 1:5 return vec vec = (1,2,3,4,5)
-find(vec, expression operator, criteria)
Returns indices of a vector that meet a certain criteria -will return an empty vector if criteria is not met
What types of vectors are there in Matlab
Row vectors 1xn Column vectors nx1 scalar 1x1
How can we perform scalar multiplication on vectors and matrices
Simply multiply or divide a vector or matrix by the number you wish.
What is a step value?
The value by which numeric values is to be separated by in a run of data eg. vec= 1:2:9, will return a vector from 1 to 9 by 2s
What are logical vectors used for in MATLAB
They use relational expressions hat result in true or false -can pull elements from a double array with a corresponding logical array by using this method
What is the purpose of an Output statement?
To display strings and/or the results of expressions -allows for formatting or customizing display
What are logical values represented with numerically?
True = 1 False = 0 This allows for logical expressions to have mathematical functions performed on them
How can we element by element multiplication and division between two vectors or matrices?
We use dot operation which is the use of the common operators in MATLAB preceded with a dot
How can we concatenate vectors in Matlab
[put both vectors][in square brackets and assign]
What is a scripts
a sequence of MATLAB instructions that is stored in an m. file and saved
What are plot color symbols and description
b - blue c - cyan g - green k - black m - magenta r - red w - white y - yellow
How can a column vector be created?
by putting values in square brackets separated by a semi colon you could also transpose a row vector with an '
clear command
clears out all variables so they no longer exist
clear variablename1 variablename2 command
clears specific list of variables
plot commands
clf - clears figure window by removing everything in it figure - creates a new window without args, calling it figure(n) hold - freezes the current graph and superimposes new plot on current plot legend - displays strings passed to it in a legend box grid - displays lines on graph
How are matrices indexed
column wise
-char()
converts character to numeric equivalent
-numequiv()
converts characters to their numerical equivalents
-zeros(x,y)
creates a matrix of zeros with dimensions x by y
-cross(vec(x,y,z), vec2(x,y,z))
cross multiplies all vector elements -can only be used with vectors of three elements
-nthroot( , )
finds the desired root of a value with (value, number of root)
-fliplr()
flips a matrix from left to right
-flipud()
flips a matrix up and down
How do you separate rows and columns in a matrix?
in square brackets, use spaces or commas to separate row elements and ; to move to the next row
What are plot symbols and description
o - circles d - diamonds h - hexagons p-pentagons + - plus sign . - point s - square * - star v- down triangle < - left triangle > - right triangle ^ - upper triangle x - xmark
Common constants
pi = 3.14159 i and j = sqrt -1 inf = infinity NaN = not a number
-plotonepoint()
plots a single point of x and y
-load(filename)
reads a file name
What two functions return division remainders
rem(,) and mod(,)
-any(vec/matrix)
returns 1 if any elements are true and 0 if none are true
-logspace(x,y,n)
returns a ector of values ranging 10^x to 10^y of n values
-linspace(x,y,n)
returns a vector of n values in x to y range
-isequal()
returns logical all or nothing (1 or 0)
-size(mat)
returns the dimensions of rows and columns [r,c] of mat
-length(mat)
returns the highest number between rows and columns of a matrix
-numel(vec/mat)
returns total # of elements in vector or matrix
-rot90(mat, n)
rotates a mat 90 degrees counterclockwise n times
-diff(vec)
runs a 'running difference' between vector elements -this is done columnwise for vectors
-lookfor(H1line)
searches for script comments
What are vectors and matrices used to store?
sets of values, all of which are the same type
help command function
shows a list of help topics related to a function
Why will running 3<x<5 be returned as true regardless of the value of x?
the expression is assessed stepwise, meaning 3<x is evaluated, changing the of x to 0 for false or 1 for true. Now the subsequent expression is evaluated, since 0 or 1 is smaller than 5 (x<5) the expression will be true This is why you must separate expressions into two parts (3<x && x<5)
Are MATLAB compiled or interpreted
they are interpreted
What can ellipses be used for in Matlab?
they can be used to continue long expressions on the next line
Explain matrix multiplication
to multiply matrices to find a third matrix; -# of rows in matrix 1 must = # of columns in matrix 2 -Order of multiplication is significant if you multiply 1x4 with a 4x1 vector, you get 1x1 but flip the order and you get a 4x4!
-repmat(mat,x,y)
used to create a larger matrix comprised of the original matrix
how can one create true and false vectors and matrices?
using -true() and -false()
How are algorithms created
with a modular approach in which the solution to a problem is broken down into several steps. -These steps are refined until small enough to be managable tasks
How can one create an empty vector in Matlab
with empty square brackets [] -you can add to this vector as you would normally -vector values can be deleted with -vec(n) = [] -does not apply to matrices due to uniformity --but you can delete entire rows or columns with :
What are Modular programs in relation to the main program
Modular programs - A program in which the solution is broken down into modules and each is implemented as a function Main Program - The script that calls modular functions
Whos command
Shows variable type, number of bytes used for storage, and the size
What is difference in the header of functions that do not return values
There are no output arguments or assignment operator
-fzero(function, value)
finds the zero of a function near a specified value
Polar form
Uses the complex plane in which horizontal plane is the real component and the vertical plane is the imaginary component
format for using FOR loops on vectors
for i = 1 : length(vec) do something with vec (i) end This is not common practice and likely build in functions and operators are used instead because its a pain in the ass
simple example of a for loop
for i = 1:5 fprintf('%d\n', i) end 1 2 3 4 5
How does one display the length of each string stored in a cell array cell?
for i = 1:length(names) disp(length(names{i})) end
How would one fully display a vector of structures via a loop?
for i = length(packages) disp(packages(i)) end
How are for loops used on vectors and matrices
for loops go through all elements of vectors and perform some action on all
What does pixels stand for
picture elements
What does varargin do?
stores any number of input args in a cell array
-unique()
will return all non-repeated values in ascending without 'stable'
-setxor(vec1,vec2)
will return all non-repeated, shared values of both vectors in ascending unless otherwise specified
-diag(mat)
will return column vector of a mat diagonal value -can also be used to take vector of length n and create mat
-isfield(structure, field)
will return logical true if is a field else false
-isstruct(structure)
will return logical true if is a structure, else logical false
What is the range of brightness in hue for 8 bit image RGB
0 to 255
what is the range of brightness in hue for 16 bit image RGB
0 to 65535
What is default slider range?
0-1 but can be changed with min and mix
Leading blanks
blank spaces at the beginning of a string
trailing blanks
blank spaces at the end of a string
What are the three steps to using lower level input and output func.?
1. Open file 2. Read from, Write to, or Append the file 3. Close the file
What are the three different operations that can be done to a file?
1. Reading from 2. Writing to 3. appending to
What are the three different operations performed on files?
1. read from 2. write to 3. append to
What are the two main search algorithms?
1. sequential search 2. binary search
How are three ways that images are stored
1. unassigned 8 bit (uint8) 2. unassigned 16 bit (uint16) 3. some stored as double
What are the two ways to get solutions to sets of equation in MATLAB?
1. use matrix representation 2. using the -solve() function in toolbox
What are the different ways vectors of structures can be passed to functions
1. using entire structure vector 2. just using one element (single structure) 3. single field within a single structure
What is the comment symbol for MATLAB
% followed by a description
placeholders for fprintf
%d used for integers %f used for real numbers %c used for single characters %s used for strings
How do you create a multiple line comment
%{use this format%}
What are some example properties for textbox object
'BackgroundColor' & 'EdgeColor' for the border and fill of the textbox respectively
What are two basic types for number storage?
'double' and 'single
what is the type of symbolics
'sym', works with strings
Animation functions for 3D plots
-comet() = does similar animation to comet() -mesh() = draws a wireframe mesh of 3D points -surf() = creates a surface plot using color to display parametric surfaces
What strings can be used to remove white space characters
-deblank() - removes trailing blanks of a passed string -stringtrim() - removes leading and trailing blanks but not blanks in the middle of the string
How can one find the properties of the computer screen
-figure(0)
How can object properties be displayed
-get() function and passing the handle of the plot object
format for calling an image
-image(mat) where mat represents the colors in an mxn image (pixels)
How can you read or write to image files?
-imread() -imwrite()
How can one create a three dimensional matrix
-mat(x,y,z)
Different plot types functions
-plot() -bar() -barh() -area() -stem() histograms, stem plots, piecharts, and area plots
Index of general plot functions
-plot() plots a line graph of data -bar() plots a bar graph of data -clf() clears the figure window -figure() creates numbered figure windows -xlabel() -ylabel(), -legend() for labeling -sprintf() used to customize labeling with loops -axis() changes the axis from default range & domain grid and hold command prints grids or not, superimposes graphs or not -subplot() creates a matrix of plots in the current figure window -loglog() uses logarithmic scale for both the x and y axes -semilogy() uses linear scale for x axes and log for y axes -semilogx() uses log scale for x and linear for y axes
How can you change a property
-set(object handle, 'property name', property value)
List of set operator functions
-union() -intersect() -unique() -setdiff() -setxor()
Case changing functions
-upper() changes strings to all upper case letters -lower() changes strings to all lower case letters
What are the different methods to plotting complex data
1.plot real vs. imaginary components with -plot() 2.plot only real parts using plot 3. plot real and imaginary on one figure using plot 4. plot the magnitude and angle using polar -default is real vs. imaginary components
Common relational expression operations
> greater than < less than >= greater than or equal to <= less than or equal to == equality ~= inequality || or && and ~ not
What is the syntax for a anonymous functions
@(arguments) functionbody; - this stores the function handle and ex. circarea = @(radius) Pi * radius .^2
What is a program?
A set of scripts and functions
What is a polynomial curve
A simple curve of different degrees/orders
while loop general format
while condition action end The action is executed as long as the condition is true - || and && can be used in while loops
-str2func()
will convert a string to a function hand ex. str2func('sin')
'ez' before plot domain
will convert symbolic to numeric to plot
uicontrol('name of a property', its value)
will create GUI in the current figure window with specifications
-Pie()
will create a pie chart of vector -each slice represents the percentage of whole vector sum -instead of % contribution, you can label the sections of the pie charts with a cell array in 2nd arg pie(vec, {'labels})
-issorted(vec)
will return logical true if sorted in ascending, false otherwise
-func2str()
will return the definition of an anonymous function
-sound(y, Fs)
will send a sound signal to speakers -y is the sound signal amplitude -Fs is the frequency --y can be nx2 matrix for stereo sound --Fs can be omitted which will default to 8192 Hz
[r,c] = size(map)
will show dimensions of current colormap with r representing number of colors
load command format stipulations
works as long as the data in the file are "regular" which refers to having same type and formation every line (matrix) -If not the case, lower level file input functions used -opening file needed first, finding or creating file and indicating -when read through is finished, the file must be closed
-save(filename)
writes to files
What is the difference between writing an appending?
writing is from the beginning and appending is from the end
difference between ||/&& and |/&
|/& used to compare logical vectors ||/&& used to convert to scalar
what is the magnitude or absolute value of a complex number
|z| = sqrt(a^2 + b^2)
What is a solutions set?
All the possible solutions to a system of equations -all sets of values of unknowns that satisfy the equations -there can be either no solutions, one solution, or infinitely many solutions
-strtok()
Breaks string into two pieces; called multiple ways -receives one input argument string and then looks for a delimiter
Structures
Data structures that group together values that are logically related, are not the same thing and not necessarily the same type -Store different values in separate "fields of the structure
What is computer programming
Multiple steps of statements in a computed script bundled together for convenience
Barebones requirements of functions
Must be defined with a header & a body
How do you combine like terms in symbolic expressions in MATLAB?
Must denote symbolic variables prior to expressions to do this -syms(x y z) can be used to avoid redundancy
Do scripts interact with the variables that are defined in the command window?
No they are used in scripts but not functions
General format of if statement
If condition then action end -the condition is a rational expression that is logically true or false -the action is a statement or a group of statements that will be executed if the condition is true -the end statement closes
What is implied if the result of multiplying a matrix (A) by another matrix when the product is the identity matrix
It implies that the second matrix is actually the inverse of the original matrix A * A ^-1 = I to actually multiply matrices is a complex process, so using inv(mat) is used instead
What is vector indexing
It is an alternative to sorting vector in which values of the original vector are labeled in a specified order ex. originalvec(indexvec(i)) would be ith lowest or highest value of original vector
What is the format for the extent of the textbox object?
It is given by a vector of [x, y, width, height] -x and y are coordinate of the bottom left corner of text box --The width and height use units specified by the x and y axes
What is a code cell?
It is the process of breaking scripts into sections
How does one customize plots
The "plot tools" icon in the figure window will bring up the "property editor" & "plot browser" ex. barh(x,y,width) or pie(vec,variable,labels)
What is a vector of structures?
Structures that have multiple variables which share the same fields -These are not matrices but instead vector of structures
How does one perform math on symbols and not numbers
Use the symbolic math toolbox, something I gotta download
How does one delete an element from a cell array?
Use vector indexing and an empty vector
load and save commands
Used to read from a data file into a matrix and write from a matrix into a data file
Can function be passed to all fields of vector structures?
Yes ex. sum([sturcture.field]) ans = sum of fields
Why is the normal way to create vectors of structures generally inefficient?
You should pre allocate the vec of structures by starting creation with the last indexed structure
Is it possible to have multiple callback functions within a GUI function?
Yes, for example you could have two buttons, each with a unique reaction
Timing command
built in to examine execution time tic script toc can also use run and time
How can you reconstruct a continuous sound
by analyzing a set of discrete measurements of the original sound
How can one find a matrix inverse by reducing an augmented matrix
by augmenting a matrix with an identity matrix of the same size, then reducing it, yields the inverse matrix -[ALL] -> reduce it [IIX] X will be A^-1 -rref([a eye(size(a)])
-hist(vec)
by default returns a 10 bin histogram -can specify bins with a second argument - can returns a vector with frequency of occurrence?
How is sequential search accomplished?
by looping through a vector element by element starting from the beginning
What is the branching component of a switch statement
casen where n is the conditional outcome number
What type of data is a cell array?
cell
sound mat files
chirp gong laughter splat train handle
How does one find the class of an anonymous function
class(header)
-collect()
collects coefficients
What is extrapolation?
estimating outside the bounds of the recorded data
what is the format for the polynomials of complex numbers
example roots([1 1 -3 +2i]) ans = -2.796 + 0.532i, 1.3796 - 0.532i OR polyval([1 1 -3 +2i], 3) = 9+2i
Ifelse statement
executes an action if a condition is true, if the condition is false, another action is executed
Recursive example
factorial iteration - n! = 1*2*3*4.....n recursive factorial - n! = n * (n-1)! -This is a factorial defined in terms of another factorial --A base case (ex. 1! = 1) stops recursion this is required to avoid a recursive infinite loop
example of plotting data from a file with textscan()
compsalesbarpie.m fid = fopen('compsalesdat') if fid == -1 disp('file open unsuccessful') else filecell = textscan(fid, '%f %s') subplot(1,2,1) bar(filecell{1}) xlabel('divisions') ylabel('sales(millions)') set(gca,'XTickLabel',filecell{2}) subplot(1,2,2) pie(filecell{1}, filecell{2}) title('Sales in millions by division') end closeresult = fclose(fid) if closeresult ~= 0 disp('file close unsuccessful') end end
-char(first, last)
concatenates vertically first last -creates a matrix with trailing blanks for uniformity
What are two types of data we can acquire
continuous or discrete
-Char(cell array)
converts cell array to character matrix
str2double
converts from a string containing a number to a double number -better than str2num but only works with a scalar, not vector
-str2num()
converts from a string containing numbers -if spaces in the string, a vector will be created
-int2str()
converts from an integer to a string
-sym2poly() and poly2sym()
converts from symbolic expressions to polynomials and vice versa ex. mypoly = [2 0 -1 0 5] poly2sym(mypoly) ans = 2x^4 -x^2 +5 sym2poly(ans) ans = [2 0 -1 0 5]
Example of creating an index vector
createind.m function indvec = createind(vec) len = length(vec) indvec = 1:len for i = 1:len-1 indlow = i for j = i + 1 :len if vec(indvec(j))<vec(indvec(indlow)) indlow = j end end temp = indvec(i) indvec(i) = indvec(indlow) indvec(indlow) = temp end end
-meshgrid()
creates (x,y) points for which z = f(x,y)
-bar3()
creates 3D bar plot
-plot3()
creates 3D line plot
-complex()
creates a complex number based off of the components (real, imaginary)
-subplot(r,c,n)
creates a matrix of plots in current figure window r is rows, c is columns, n is the number of the plot within the matrix
-uibuttongroup()
creates a mechanism for grouping together the buttons of a group in which only one can be chosen at a time
What does the plots tab do?
creates advanced plots -first create variables and then select the tab --based on this usable plots are highlighted; clicking will plot the data using that function and open window w/ that plot (be sure to highlight vars)
General format for opening a file
fid = fopen('filename', 'permissions string') -be sure to error check in scripts
-polyfit()
finds best fit straight line that goes through a data set -three args; x and y vectors rep data and the degree of desired polynomial -we can then use polyval to examine the estimation at each value
-factor()
finds factors
-mean()
finds the arithmetic mean of vector -matrix columnwise --can be row-wise with 2 in 2nd argument
-max()
finds the maximum value of a data set and the indices of this number -if matrix will return each column val/ind
-min()
finds the minimum value of a data set and the indices of this number -if matrix will return each column val/ind
Programming method example of data storage to vector avoiding sentinel while using while loop;
findvalwhile.m %Reads data from a file, but only plots the numbers up to a flag of -99 uses a while loop load experimentdata.dat i = 1; while experimentdat(i) ~= -99 newvec(i) = experd(i); i = i + 1 end plot(newvec, 'ko') xlabel('Reading#') ylabel(weight(pounds)') title('First Data Set')
Efficient method example of data storage to a vector avoiding sentinel while using while loop
finval.m %Reads data from a file, but only plots the numbers up to a flag of -99. Uses find and colon operator load experimentdata.dat where = find(experimentdata ~= -99); newvec = experimenntdata(1:where-1)
Appending to files format
fopen('filename', 'a') -fprintf can also be used to append to an existing file --using this in a loop, we can write onto the end of a file until closure
General format for the FOR loop
for loopvariable = range action end
general format for nested loops
for loopvarone = rangeone action one for loopvar2 = range 2 action two end end
How can you use lower level functions to write to files
fprintf - can be used to both write to and append files -you can specify a file for fprintf to print to ex. fprintf(fid, 'format', variable)
what form is symbolic math in
fractional
Variable number of output arguments example
function [arrtype, varargout] = typesize(inputval) %returns if input is scalar vector or matrix [r,c] = size(inputval) if r == 1 && c ==1 arrtype = 's'; elseif r==1 || c==1 arrtype = 'v'; varargout{1} = length(inputval) else arrtype = 'm' varargout{1} = r varargout{2} = c end end nargout can be used to make if-else statements to include optional output args
example of varargin
function area = areafori(varargin) n = nargin radius = varargin{1} if n = 2 unit = varargin {2} if unit == 'i' radius = radius * 12 end end area = pi * radius.^2 end calculates the area of a circle in feed or
Whats a function handle and what is it used for?
function handles use the @ operator and can assign anonymous, built-in, and user defined functions with @
what are the two main formats for functions with multiple input arguments
function outarg = fnname(varargin) function outarg = fnname(input args, varargin)
Nested loop example with multiplication matrix
function outmat = multtable(rows, columns) %multtable returns a matrix which is a multiplication table table %multtable (nrows, ncolumns) % pre allocate matrix outmat = zeros(r,c) for i = 1:rows for j = 1:cols outmat(i,j) = i + j end end end
-rref(a, b)
function that performs reduced row echelon form elimination for unknowns
-num2str()
function to convert a number into a string value for display, default is four decimal places
what are two main formats for multiple output argument functions
function varargout = fnname(input args) function [outputargs, varargout] = fnname(input args)
How do you call a function
function(criteria)
What is the general format for a user defined function?
functionname.m function outputarg = functionname(input arg) %comment describing the functions purpose statements include putting a value in output arg end
-figure()
functions numbers windows sequentially 1,2, so on
Recursive functions
functions that call themselves
what are nested functions?
functions within functions
How do you return a property value of a plot
get(handle, 'property')
-gca()
gets handle of axes
buttongroup coding example
grouph = uibutongroup('parent', f, 'Units', Normalized', 'Position', [x y w h], 'title', 'choose color', 'selectionchangefcn', @what to do) function what to do(hobject, event data) which = get(grouph, 'selectedobject') if which == toph set(texth, 'foregroundcolor','blue') else set(texth, 'foregroundcolor','blue')
Example of adding GUIs to a plot
guiSliderPlot.m f = figure('Visible', 'off', 'Position', [x y w h] 'color', 'white') minval = 0; maxval = 4*pi slhan = uicontrol('style', 'slider', 'position', [x y w h], 'min', 'minval', 'max', maxval, 'callback', @callbackfn) hmintext = uicontrol('style', 'text', BackgroundColor', 'white', 'position', [x y w h], 'string', num2str(minval)) hmaxtext = uicontrol('style', 'text', BackgroundColor', 'white', 'position', [x y w h], 'string', num2str(maxval)) hsttext = uicontrol('style', 'text', BackgroundColor', 'white', 'position', [x y w h], 'visible', 'off') axhan = axes('Units', 'Pixels', 'Position', [x y w h]) set(f, 'Name', 'sliderexamplewithplot) movegui(f,'center') set([slhan, hmintext, hmaxtext, hsttext, axhan], 'units', 'normalized') set(f, 'visible', 'on') function callbackfn(hobject, eventdata) num = get(slhan,'value') set(hsttext, 'visible', 'on', 'string' ,num2str(num)) x = 0 : num/50 : num y = sin(x) plot(x,y) xlabel('x') ylabel('sin(x)') end end
GUI coding example for a slider
guislider.m function guislider f = figure('Visible', 'off', 'color', 'white', 'position' [x,y,w,h]) minval = 0 maxval = 5 slhan = uicontrol('style', 'slider', 'position', [x,y,w,h], 'min', 'minval', 'max', 'maxval', 'callback', '@callbackfn') hmintext = uicontrol('style', 'text', 'BackgroundColor', 'white', 'position', [x,y,w,h], 'string', num2str(minval) hmaxtext = uicontrol('style', 'text', 'BackgroundColor', 'white', 'position', [x,y,w,h], 'string', num2str(maxval) hsttext = uicontrol('sytle', 'text', 'BackgroundColor', 'white', 'position', [x,y,w,h], 'visible', 'off') set(f,'name', 'slider example') movegui(f,'center') set(f, 'visible', 'on') num = get(slhan, 'value') set(hsttext,'visible', 'on', 'string', num2str(num))
Example of GUI program with an edit box
guiwitheditbox.m function guiWithEditbox f = figure('Visible', 'off', 'color', 'white', 'position, [360, 500, 800, 600]) set(f, 'Name', 'GUI with editable text box') move(f,'center') hsttext = uicontrol('style', 'text', 'BackgroundColor', 'white', 'position', [100, 425, 400, 55], 'string', 'Enter your string here') set(f, 'visible', 'on') function callbackfn(hobject, eventdata set([hsttext huitext], 'visible', 'off') printstr = get(huitext,'string') hstr = uicontrol('style', 'text', 'BackgroundColor', 'white', 'Position', [100, 400, 400, 55], 'string', 'printstr', 'ForegroundColor', 'Red', 'FontSize', 30) set(hstr,'visible', 'on') end end
format for using -line()
handle = line(x, y, 'property', specify, 'property' specify)
format for using -text() function
handle = text(x,y,'text string') -where x and y are coordinates -in this case special characters can be used with \specchar
-strcat(first, last)
has come effect as normal concatenation except removes trailing blanks and keeps leading blanks
format for inserting pushbutton for activating code
hbutton = uicontrol('style', 'pushbutton', 'string', 'pushme!!!', 'position', [x y w h])
What is main format for error checking
if input is correct execute code else throw error message
What is an object
includes graphics primitives such as lines and test as well as the axes used to orient the objects
Common format for input prompt format for scripts
input('enter a certain value: ') -for a character or string use 's'
What does transpose?
interchanges the rows and columns apostrophe as operator
what does the clear command do?
it eliminates variables
What is uipanel
it is a means of grouping together user interface objects
What is subplot indexing?
it is the size of matrix for first two arguments followed by a number which indexes the plot ROW-WISE
What is the arithmetic mean
it is the sum of all values divided by # of all values in a data set
What will -sort() do to a string?
it will work as it does using numbers, sording ASCII in the numerical equivalents, scrambling the string values
What does a counted loop do?
iterates a predetermined number of times
How can we extrapolate data
one way to extrapolate is with a best fit curve which involves finding best polynomials to fit the data
-bar3 and -barh arguements
only pass the y and z vectors to functions -matrices can also be passed with rows and columns being represented with x and y values and z representing the n value
-fopen('filename', 2nd arg)
opens a file, returns an integer as the file ID or -1 if fails -2nd arg, read is default (r), write(w) or append(a) changes
format for nested functions
outer function header body of outer function inner function header body of the inner function end inner function more body of outer function end outer function
What is the cavoite to nested functions?
output args from inner nested funcs cannot be used in outer function
How can we extrapolate with polyval
passing a value to the created function outside the bounds of the included data
function functions
passing functions to other functions
Function Functions
passing functions within functionsoften times used whith function handles ex. passing sin to a function to plot a value of x will return an error but function handle @sin will run the sign of the desired values
strcmpi(string1, string2)
performs case-insensitive comparison between string1 and string2 for equality. If the strings are equal, they must have the same content (independent of case) and length. strcmpi('something', 'SOMETHING') True strncmpi performs same as strncmp
fplot(fnhandle, [xmin, xmax])
plots a function between limits that are specified
Example of plotting subplots with a loop for different plot types
plotxywithcell.m function plotxywithcell (x, fhan, rca) y = fnhan(x) for i = 1 : lenrca subplot(1,lenrca,i) funh(x,y) title(upper(rca{i})) xlabel('x') ylabel(fun2str(fhan)) end creates 3 representations of the same data using different plot types
example of plotting extrapolated data with polyfit
polytemp.m #plots data and quadratic best fit line on some figure x=2:6; y= [65 67 72 71 63]; coefs = polyfix(x,y,2); curve = polyval(coefs,x); plot(x,y,'ro',x,curve) xlabel('Time'); ylabel('Temperatures'); title('Temperatures one afternoon'); axis([1 7 60 75])
how can we use -polyval for discrete points to interpolate x of 2 & 3
polyval(coefs, 2.5) ans = midpoint of dependent variable
-menu('instruction', 'option1', 'option2', option3')
pop-up window that displays a function as a heading and arguments used as choices to be selected by the user
example of reading an image file
porchimage = imread('snowyporch.JPG') size(porchimage); ans = 2848 4272 3 class(porchimage); ans = uint8
Format for true color matrix
m x n x 3 where m and n are coordinates and 3 is the color component in which 1 is red, 2 is green, and 3 is blue
Algorithm for nested function callbackfn
make the previous GUI objects invisible get the string that the user typed create static TB it print Make new object visible
Bounded matrix
matrix of 0s with the exception of the main diagonal and diagonals above and below -also called tridiagonal matrix
matrix function for bar graphs
matrix passed -bar and -barh will group values in each row. MATLAB will color column values with the same color for row(i) bar(var, 'stacked') will sum x values in each row
How does one refer to values of a matrix?
matrixname(row, column) -this can be iterated with the colon function --using : in place of rows or column selects all elements
polar form for complex numbers
rcos(theta) + rsin(theta)i z = r(cos(theta) + i sin(theta)
-fgets() and -fgetl()
reads strings one at a time -fgets keeps newline character Used in a loop to read line to line
-textscan()
reads text data from a file and stores in cell array
-strfind()
receives two input arguments to find occurrences of a substring within a string ex. strfind('abcdabcdedd', 'd') ans = 4, 9, 11, and 12 -if no occurrences, an empty vector will be returned
-isempty()
recognizes empty vectors and strings from input functions
format for calling a rectangle object with a specified curvature
rect('position', [x,y,w,h], 'curvature', [0-1,0-1] -set(rh, 'property', values) can also be used to set specifications
-setdiff(vec1,vec2)
returns all values found in vec1 but not in vec2 -asc order unless specified otherwise -input order changes outcome vector
-union(vec1,vec2)
returns all values from vecs w/o repeating in ascending order -'stable' 3rd arg returns order of appearance --input order of vectors matter when using stable
-isspace()
returns logical true for every character that is a white space character
iscellstr(cellarray)
returns logical true if cell array is all strings, else false
-feof()
returns logical true if the end of a file has been reached
-ischar()
returns logical true if vector is a character type and logical false if not
-ismember()
returns logical vector of length(vec1) with element of vec1 also in vec2 ==true and false if not -argument order matters here -will not sort
-conj()
returns the complex conjugate
-real() & imag()
returns the real and imaginary components of complex numbers
-intersect(vec1, vec2)
returns values that can be found in both vectors -sorted in ascending unless otherwise specified
-sort(vec)
returns vec in ascending order -descending order if specified in 2nd arg -avoids pain in the ass loop for smallest value -sorting creates duplicate vectors --matrix sorted columnwise, must specify if row desired
-iskeyword()
returns whether or not a string is the name of a keyword in matlab -This helps users know availability of variable names at the global level
What does sampling continuous data result in?
samplings provides data in the form of (x,y) points x=time unit while y=dependent variable
General format for saving to a file
save 'filename' matrixvariablename_ascii
How do you save just one variable to a file?
save filename variablename
How can one save an anonymous function?
save to a mat file and then loaded when needed
What is the difference between save and append?
saving overwrites, append adds to
What are basic elementary row operations
scaling (multiplying by a nonzero scalar) interchanging rows replacement (adding to or subtracting from a multiple of another row
example of sequential search
seqsearch.m function index = seqsearch(vec, key) len = length(vec) index = 0 for i = 1 : len if vec(i) == key index = i end end end
what is the main diagonal of a matrix?
set of terms in which row and col indices are the same
'style' property
defines the type of an object as a string -ex 'text' is the style of a static text box (normally used as a label for other obj. in the GUI for instruction)
-xlabel() & -ylabel()
denotes the axis titles
-title()
denotes title of a plot
Differentiation
derivative of y = f(x) -is written dy/dx f(x) Defined as the rate of change of y with respect to x -slope of the line tangent to the func at a given point
checkcode command
detects potential problems within scripts and functions
What is the purpose of standard deviation and variance
determines the spread of data, normally in terms of the arithmetic mean
-Pie3()
shows data from a vector as a 3D pie chart
How does one place an image in a GUI
simply using the axis to locate the image -this process can also be used in conjunction of a slider to create a dimmer
Triganomic functions
sin = sine asine = inverse sine sinh = hyperbolic sine asinh = inverse hyperbolic sine sind and asind = in degrees
common usages of vectors and matrices as function arguements
sin(vec) - the sin of all vec values sign(mat) - sign of integers in matrix in same format min(vec) - minimum value of a vector max(vec) - maximum value of a vector sum(vec) - sum of all elements of a vector prod(vec) - multiplies all elements of a vector cumsum(vec) - running sum of vector elements cumsum(vec) - running product of vector elements --For matrices, all of these functions are performed columnwise. If rowwise preferred, transpose
How are discrete signals and sampling frequency represented in MATlAB?
discrete signals = vectors sampling frequency measured in Hz
disp() and fprintf() on structures
disp() - displays whole package or a field fprintf() - only prints individual fields
sign command
displays +1, 0, or -1 to denote the sign of an arguement
-colorbar()
displays a color scale in a plot
-celldisp(cellarray)
displays all elements of a cell array
-movie()
displays recorded movie frames of a plot -frames recorded in a loop using -getframe()
-disp()
displays straight up version of vectors and matrices
-help(function)
displays the comments -organizations have standards for their comments like 1. name 2. description 3. format 4. args description in and out 5. variable descritpion 6. programmer name/date 7. revision info
help command
displays the first comment of a script
type('file')
displays the type of a file
-simplify()
does what it can to simplify expressions
-bar()
draws a bar chart
-barh()
draws a horizontal bar chart
-area()
draws a plot as a continuous curve & fills in the area underneath the curve which its created
-stem()
draws a stem plot
How can you dim or brighten an image?
multiply numbers by a constant number will change the hue -use imwrite(value, 'imagefile')
What is the syntax for assigning a element of a cell array to a variable
mycellmat{1,1} = variable
Example of using the menu function
mypick = menu('pick a pizza','cheese','pepper','mush') switch mypick case n disp('order n pizza')
Example of common practice of sorting vec of structs by fields
mystructsort.m funtion outv = mystructsort((structarr),(fname)) for i = 1:length(structarr)-1 indlow = i; for j = i + 1 : length(structarr) if structarr(j).price<structarr(indlow).price indlow = j end end temp = structarr(i) structarr(i) = structarr(indlow) sturctarr(indlow) = temp end outv = structarr end
format for removing outlier from vectors
newvec = oldvec(oldvec ~=min(oldvec) oldvec~=max(oldvec))
What is the most efficient way to create a vector structure?
structurename = struct('firstfield', struct(secondfield, val), 'first field', struct(secondfield, val)) - alternatively, inner structures can be created and then passing them to struct(inner structures)
How can vector of structures be referenced?
structurename(number) for field reference structure.field(number)
-subs()
substitutes a value in place of a symbolic variable -symbol should be specified in the middle argument
How can you import multiple file formats in MATLAB
use "ImportData" from the Home tab -This activates import tool which allows for importing a variety of file formats
How do we find the abs and theta of a complex number?
use -abs(z) and -angle(z)
If a function returns multiple values, how do you store those values?
use multiple variables to store in vector form
How can you get index values of vectors passed to set operator functions?
use output vecs v1 = [6,5,4,3,2] v2 = [1,3,5,7] ex. [outvec, index1, index2] = intersect(v1,v2) outvec =[3,5] index1 = [4,2] index2 = [2,3]
Things to keep in mind for writing efficient code in MATLAB
use scalar and array operators use logical vectors create built in functions pre-allocate vectors use sum and prod cumsum and cumprod min and max any, all, and find isletter, and isequal
How can you display default properties of a figure
Assigning a handle to a figure and using get(hdl)
-gcf()
gets handle of figure
-var()
calculates the variance around the arithmetic mean of a dataset
-ones(x,y)
creates a matrix of ones with dimensions x by y
-tril()
lower triangular matrix has all zerose above the main diagonal
What are the three specifications in plot strings?
Colors, symbols, and line types
What are set operators?
Combine data of two vectors into a single result
3D shape functions
-sphere -cylinder
What is a sentinel?
a marker between data sets used to denote separation
What is interpolation?
estimating value between data
-trace()
sum of diagonal elements in a square matrix
What is an algorithm
A sequence of steps needed to solve a problem
What is the branching component of an if statement
elseif and else branches
'\n'
denotes new line
-end
refers to the last element in a vector or matrix
How does one append variables to a .mat file
-append option does this -need to specify variables --if just -append is used then the entire workspace is added and overwrites file data
What is the difference between cell array and structures
-Cell arrays are indexed and can be looped -Structures are not indexed. values referenced with field names -Both can contain values of different types
What is done with code cells
-One can run one cell at a time and can publish the code in HTML format with plots embedded and formatted equations --To do this, use double comment symbols at the start of code line, these become the cell titles --You can also run cells independently of one another from the editor options ---Selecting publish here will publish by default in HTML
Three categories of functions
1. Functions that calculate and return 1 value 2. Functions that calculate and return 1+ values 3. Functions that accomplish tasks like printing without returning a value
What are two selection and branching options
1. If statement 2. switch statement
What are the different types of errors
1. Syntax = mistakes in the language, things like quotations or spelling variables incorrectly, often MATLAB corrects 2. Runtime = Found when a script or function is executing. An example is referring to a nonexistent element 3. Logical = A mistake in the reasoning from the programmer, but is not a mistake in the programming language. Parsed with error checking
What are 2 matrices used when representing an image w/ colormap?
1. The colormap matrix which has dimensions p x 3 -p represents # of colors which each row stores three real numbers referring to the RGB component contr. 2. The image matrix with dimensions mxn -all elements are indexed into the colormap matrix, which means that it is an integer ranging from 1 to p
What are the two basic methods for creating GUIs?
1. Write the GUI program from scratch 2. using the build in Graphic User Interface Development Environment (GUIDE)
What are the two main types of loops
1. counted (for) 2. conditional (while)
How do you create an index vector (3 steps)
1. initialize values of index vector to be indices for the length of original vector 2. use any sort algorithm but compare elements using index vector to index into it = originalvec(indexvec(i)) 3. When sort alf. calls for exchanging values, exchange elements in index vector, not the original
What are 5 main core object types
1. line 2. text 3. rectangle 4. patch 5. image
How are pixel colors represented in MATLAB
2 ways to do this 1. true color (RGB) in which three color components are stored in separate columns Indexed into a colormap, in which the value stored is an integer that refers to a row in a matrix called colormap
What does second argument of strtok return
2nd argument consists of alternative delimiters
What is a slider?
A GUI object that can be created which can be controlled by clicking arrow to move it up or down, or by sliding the bar w/ the mouse
What is a delimiter
A character or set of characters that act as a separator within a string -Default delimiter is a white space character and will return string up delimiter -leading blank ignored in default ex. sentence 1 = 'Hello There' [word, rest] = strtok(sentence1) word = 'Hello' rest = 'There'
callback function
A function that is triggered by another function when something is true.
What is a subfunction
A function within a function
symmetric matrix
A square matrix that is equal to its transpose aij = aji for all i & j
What is a loop?
A statement in code that allows other statements to be repeated
What is a nested structure?
A structure in which at least one member is in itself a structure
What is done when assigning -get(plot handle) to a variable?
A structure is created in which property names are the field names
What is an object handle?
A unique real number used to refer to the object
What is augmentation?
Adding columns to an original matrix -sometimes shown with a vertical line that represents augmentation -can be accomplished with square brackets [matorig mataugment]
When is a switch statement used?
Can be used in place of nested if else or an if statement with many elseif statements -used when expression is tested to see whether it is equal to one of several possible values
save command with .mat files
Can be used to write or append variables to mat files default extension of save is .mat -can save the entire workspace or a subset --be sure to set the folder prior to saving
How are properties of a textbox obtained
Cannot be obtained with -get(), however, they can be changed with -set()
What is the scope of a variable in the workspace?
Command window is the base workspace -If a variable is defined within a function it is local to that -These cease to exists outside that function
-strcmp()
Compares character to character -(car, car) = True, -(car, CAR) = False
strncmp(str1, str2, n)
Compares only first n characters of strings ex. str1 = catamarans; str2 = cathedral; strncmp(str1, str2, 3) = True
Gauss elimination
Consists of; 1. Creating augmented matrix [A b] 2. Applying ERO's to this matrix to get echelon form, or upper triangle form 3. and back substituting to solve
Gauss-Jordan Elimination Method
Consists of; 1. creating an augmented matrix 2. forward elimination to get upper tri 3. back elim to diagonal form which yields solution
How would one save print or copy/paste a plot into a report?
Copy -> Edit, copy figure, can be pasted in word doc Save -> File, save, allows to save in dif formats; .fig, .jpg .tif, and .png Modified save -> if modified properties or created not programmatically; File-> generate code will script process Print -> physically prints figure with default formats; options for this can be specified or one can save to a file with options -ex. print -dtiff -r400 plot tif
How would one display the colors in the default jet map?
Create a matrix of 1:64 and pass it to the image function
How do you create a callback function
Create a nested function within the GUI function, example; 1. create figure window 2. make color of figure white and add title/move to cent 3. create static TB w/ instruction to ender a string -'style' of this is 'edit -Callback function must be specified as the user's entry of string (necessitates a response) 4. Make GUI visible for user to see instructions & type in a string 5. When str entered callback fnc is called (two imp. args. hobject & event data) -hobject is handle of UI object that called it -eventdata can stor in structure info about user actions
How does one typically create a vector of structures
Create a structure variable as a template and add to it by indexing -ex. structure = struct(field, val, field, val) structure(2) = struct(field, val2, field, val2)
What are the indices of characters in a string
Each character of a string is an element and has the indices to reflect -This means you can call certain characters, transpose strings, create matrices of same character length etc...
What is syntax for passing structures and fields to functions?
Entire structures or individual fields can be passed ex. entire structure function profit = calcprof(packstruct) profit = packstruct.price - packstruct.cost; end calcprof(structure) ans=profit ex. fields function profit = calcprof2(oneprice, onecost) profit = oneprice - onecost; end calcprof2(package.price, package.cost) ans=profit
Structures purpose
Groups together values that are logically related into fields -fields are named aptly to help make clear what values are stored in structures -structure variables aren't arrays and cannot be looped
save command requirements
Has the same format stipulations as load command
What is the main difference between functions that return outputs in comparison to those that print
In general, functions return values and scripts print results -If a function prints a value, it cannot be stored or referred back to for later use
What is the added benefit to storing strings in cell arrays
It is very useful for strings of different lengths -unlike char(strings), there are no trailing blanks, each keeps its length
What does normalizing units mean?
It means that as opposed to specifying in pixels the position, it is done as a percentage of the figure window -ex f=figure('visible','off','color','white','units','normalized','position','[xywh])
What does an elseif statement do
It removes the inefficiency of running multiple if else statements and keeps code efficient
What does using a dot operator on a vector of structures do?
It returns all fields -useful for storage if math functions desired later
What image files are manipulatable in MATLAB
JPEG, TIFF, PNG, Gif, and BMP
What is searching in MATLAB
Looking for a key value in a list or vector
How does MATLAB manipulate strings
MATLAB has built in functions written to manipulate strings, have strings contain numbers and convert to and from numbers
What are graphic user interfaces?
Objects that allow users to have input using graphical interfaces -buttons, sliders, dials, toggles, pop-up menus
How can fields be displayed from multiple packages?
One can either use a loop method or simply; fprintf('%f\n', structure.field)
What ar nested functions?
Outer function with inner function within them
How can outputs of a for loop be stored in vectors
Pre-allocating a vector to the correct size and assigning the potential output -Can be done with the zeros function to create vector --the loop variable needs to be indexed into vector
grid argument
Renders a grid so that conceptualization of 3D plots is easier
-mode()
Returns the most frequently occurring score in a distribution -returns value not indices -if more that one mode returns the smaller value
-median()
Returns the value in the middle of a sorted data set -only for data sets that are sorted -if data set indices total is even, returns split difference -if vector is unsorted, median will sort it for you
Anonymous functions
Simple one line functions called with their handle -m file storage is unnecessary - created in the command window or script
What is sampling frequency
The amount of sample taken per unit of time -commonly measured in Hz
What is a degree of an integer
The highest exponent in the expression ex. x^3 = degree of 3 straight line = 1xt degree - ax +b quadratic is second degree - ax^2 + bx + c cubic is third degree - ax^3 + bx^2
Harmonic mean
The mean of n numbers expressed as the reciprocal of the arithmetic mean of the reciprocals of the numbers -can be generated in stats toolbox
What is the goal when a system of equations is put into matrix form?
The next steps are to solve Ax = b for x -to do this we need to isolate x by deviding both sides of eq by A -In MATLAB, we can use the divided into operator -we then multiply both sides by inverse of coefficient matrix A^-1, this gives 1x = A^-1b we can then 1. use inv(A) *b or 2. x=A\b
What is sorting?
The process in putting lists in ascending or descending order
What does a function consist of?
The word function -Names of the output arguments followed by the assignment operator (=) if the function returns values - The name of the function (same as the m file name) -input args surrounded by parentheses -A comment that describes the function purpose -The body of the function, which includes all statements --This includes placing vals in output args end
What is the value of functions that don't return values
They accomplish tasks like printing outputs -These functions cannot be called from assignment statements -They are referred to as side effects
What are core objects?
They are very basic graphics primitives -all core objects are built in functions that the help command can describe
What do functions return?
They can return one value, multiple values or nothing at all
What is the purpose of indexing into vectors of structures?
This process is used to iterate through vectors of structures in order of different fields -may be more efficient than repetitively sorting. -this will exchange entire structures as opposed to fields
What is concatenation?
To join strings together using square brackets first = 'bird; last = house; [first last] = 'birdhouse'
What is the use of a structure
To set up a database of info - Each stored variable with multiple related values called struct
What are the two ways to create a structure?
To store values in fields or by using -struct()
-trimmean()
Trims the highest and lowest n% of data values and returns the mean
How can one investigate objects, properties, their meaning and valid values?
Using the help documentation
What is a data structure
Variables that store more than one value which are logically related
How do you store a plot handle?
Various plot functions return a handle for plots, which can then be stored in a variable -This will be valid so as long as the figure window remains open
What is more efficient; vectorized coding or loops?
Vectorized coding, though many software programs don't have as powerful vectorized coding as matlab does
Event driven programming
When a user's action causes a response that is driven by a callback function -callback functions must be within the path
Recursive definition
When something is defined in terms of itself
-sprintf('something')
Works exactly like fprintf() except instead of printing, it creates a string -Useful for labelling graphs with experiment data
how do you assign multiple cells of an array to variables in one call?
[c2,c3] = cellmatrix{2:3} if cell indexing is used this way, bot referenced cells are put into an array
for loop on matrix format
[r,c] = size(mat); for row = 1:r for col = 1:c do something with mat(row, col) end end
Format for colormap matrix
a (m x n) matrix would rep coordinates by a matrix of integers, each of which is indexed into a colormap matrix of (p x 3) -p is number of colors available in map -each row in map has three components repping RGB
symbolic equation elementary example
a + a = 2*a
What is object oriented programming?
a Style of programming that represents a program as a system of objects and enables code-reuse
What is a sound wave an example of?
a continuous signal that can be sampled to result in a discrete signal
Reduced row echelon form
a form of an augmented matrix in which the coefficient columns form an identity matrix -done by forming 1's in place of a's so that b's hold unknown solutions
What is a function stub
a function definition whose statements have not yet been written
What is a recursive function
a function that calls itself (very common in programming -this is often inefficient and should be loop replaced -Recursion opposes iteration
What is a nested if else statement
a multiple criterion if else statement that at times needs to satisfy multiple criterion in order to execute code
What is a complex number?
a number that has 2 parts (1) *real* (2) *imaginary* generally written as a+b(i) real = a; imaginary = b; and i = sqrt-1
Identity matrix
a square matrix that, when multiplied by another matrix, equals that same matrix
diagonal matrix
a square matrix whose entries not on the main diagonal are all zero
What is a histogram?
a type of bar chart that shows frequency of data occurrence of values within a vector -uses 'bins' to collect values within certain ranges
what is a conjugate complex number
a-bi
mxn system of equations
a1x1 + a12x1 + a13x1....+a1nxn = b1 a2,1x1 + a2,2x2 + a2,3x3.... + a2nxn =b2 am,1x1 + am,2x2 + am,3x3.... + amnxn = bm their are m equations and n unknowns a is a matrix of coefficients, x is a column of unknowns, and be is a vector of constants
What is linear algebraic equation form?
a1x1 + a2x2 + a3x3...+anxn = b
-gtext()
allows positioning of text with the mouse over figure window -Clicking will display a text box with lower left corner origin --can be used multiple times
What functions can be used for function functions
any user defined or anonymous functions
How do you refer to the type of contents of a cell within an array?
array(cellnum)
How does one refer to specific values of specific cells in an array
arrayname{cellnum}(indexofcell)
How can you reference the contents of a cell within an array?
array{cellnum}
How does MATLAB represent polynomials?
as a row vector of coefficients ex. x^3 + 2x^2 -4x+3 = [1,2,-4,3] 2x^4 -x^2 +5 = [2 0 -1, 0 5]
General format for opening a file in a script
attempt to open file -error check open success if opened, loop until end of file for each line in the file read into string manipulate data attempt file close -error check close success
Gauss, Gauss Jordan elimination
both methods for solving systems of linear equations -both based on observation that systems of equations are equivalent if they have the same solution set -Also performing elementary row operations results in equivalence -Both methods begin w/ matrix form Ax = b of systems of equations and then augment the coeff matrix with column vec b
-repmat(struct(field, val)size,vec)
can be used to pre-allocate a vector of structures
-xlsread()
can separate numbers and text into separate matrices ex. [nums, txt] = xlsread('texttest.xls') nums = colvec of nums txt = cell array of strings
-xlswrite()
can write to excel spreadsheets -creates a spreadsheet from matlab matrices
Example of a user defined function calcarea
calcarea.m function area = calcarea(rad) %calcarea calculates the area of a circle %format of call : calcarea(radius) %returns the area area = pi * rad * rad end
-rectangle()
calling this alone brings up a figure window w/ rectangle perimeter -the position of the rectangle is given by [x,y,w,h] -x and y are lower left hand corner coordinates --w is width and h is height
-roots()
can be used to find the roots of an equation repped by polynomial ex. solve for f(x) = 0 f(x) = 4x^3 -2x^2 - 8x +3 roots([4,-2,-8,3]) ans = -1.366, 1.5, 0.366
-isletter()
can be used to logically check the data type of an input
Debugging functions
dbstop - will examine values to this point in the script dbcount - can be used to continue this script dbquit - can be used to quit the debug mode
Example of plotting from a data file with fgetl
data file format A5.2B6.4 <- four rows of this plotdivab.m fid = fopen('ab13.dat') if fid == -1 disp('file open unsuccessful') else for i = 1:4 aline = fgetl(fid) aline = aline(2:length(aline)) [compa, rest] = strtok(aline,'B') compa = str2double(compa compb = rest(2:length(rest)) compb = str2double(compb) subplot(1,4,i) bar([compa, compb]) set(gca, 'XTickLabel', {'A','B'}) axis([0 3 0 8]) ylabel('sales(millions)') title(sprintf('Quarter%d', i)) end close result = fclose(fid) if closeresult ~= 0 disp('close result not successful') end end
What is an alternate way to write a complex number?
e^i(theta)
How are objects organized?
hierarchically; A parent comes before a child and generally children inherit properties from the parent ex. Figure -> axes -> core objects and plot objects Parents -> children
Example of indexing into vector of structures
printpackind.m function printpackind(packstruct, indvec) fprintf('Item # cost pric code\n') no_packs = length(packstruct) for i = 1:len(no_packs) fprintf('%6d %6.2f %6.2f %3c\n', packstruct(indvec(i)).itemno, packstruct(indvec(i)).cost, packstruct(indvec(i)).price, packstruct(indvec(i)).code) end end
-dot(vec1, vec2)
produces matrix multi on two vectors
-solve()
solves equations and returns solutions as symbolic expressions -can be converted to numbers using double -if expression is passed as opposed to an equation, Solve will set to zero and solve rest of the equation --If its a multivariate equation, MATLAB will choose which variable to solve 4, you can specify if needed in the 2nd arg --solve can also solve systems of equation and store in field of structures, use dot operator and double in this scenario
-sortrows()
sorts the rows of a vector on the basis of the values in the first column
What are whitespace characters
space, tab, newline, or carriage return
What is a matrix with same number of rows and columns
square matrix
-std()
square root of the variance that describes spread of data
How would one index a vector element within a vector structure field?
structure(n).field(vector element)
Format for the switch statement
switch switch_expression case case exp1 action 1 case case exp2 action 2 case case expn action n otherwise action otherwise end
What are some examples of continuous data
temp/hr, speed of car every tenth of a mile, mass of a radioactive material every second it decays, and an audio of sound waves as it is converted to an audio file
what is e?
the exponential base -raising e to the power of x is super common function used in engineering and math -value is about 2.7183
geometric mean
the mean of n numbers expressed as the n-th root of their product -can be generated in stats toolbox
What is the 'action of the loop'
the statements in a loop that are repeated
What does ASCII do
the universally recognized raw text format that any computer can understand i.e. (txt and dat)
What are the requirements for complex number equality
they are only equal if real and imaginary components match ex. complex(0,4) == sqrt(-16) = 1
How are color images represented in MATLAB?
they are represented by grids, or matrices of picture elements
What do .mat files do?
they can store the names and contents of variables -variables can be written, appended, and read from --mat files are typically used within MATLAB
-triu()
upper triangular matrix that has zeros below the main diagonal
What are common matrix operations?
transpose augmentation inverse
solving 2x2 systems of equations
x1 + 2x2 = 2 2x1 + 2x2 = 6 The intersection on a plot of these two equations is at point (4,1) -this means that x1 = 4 and x2 = -1
Is it possible to have a callback function invoked or called by multiple objects?
yes, in this case, the callback function must use the input arguments to determine which object called it
How do you view the value of a vector structure?
you must index the structure number
How are complex numbers multiplied?
z1 * z2 == a+ bi * c +di = a*c + a*di + c*bi + bi*di = a*c + a*di + c*bi -b*d = (a*c -b*d)+ (a*d + c*b)i