Computer Science

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

If there was a vector vec = [1 2 3 4 5] and I entered vec(3:1) into the workspace, what would be the result? Why?

vec(3:1) --> [] 3:1 is equivalent to 3:1:1, which creates a vector beginning at 3 and going to 1 in steps of 1. It is impossible to do this in steps of 1, so this vector is an empty vector []. If you index a vector with an empty vector, then you get an empty vector.

Strings

%% NEW DATA TYPE ALERT!!!!! % char (great debate over how to pronounce it....) % We denote chars with single quotes % ex: letter = 'a'; %% How does MATLAB see chars? % Computers are run off of binary numbers (ones and zeros). So therefore, % in memory you can't really store an actual symbol or letter. Instead, % everything has to be converted into a number which then can ultimately be % converted into binary. % So, to Matlab, all chars are actually just numbers. The conversion is % through what we call ASCII Values. % ASCII --> American Standard Code for Information Interchange % By looking up the ASCII table, we can see that when we type something % like a lowercase 'a', to the computer this is actually the value 97. %% What is a String? % A string is A VECTOR OF CHARs. Everything we % talked about with vectors is applicable here. %% Creating Strings % Direct Entry word1 = 'hello'; strNum = '1'; word2 = 'bye'; % Concatenation %% Concatenate strings together and append new stuff to the end %https://www.instagram.com/samlibr/ samCaption = '(I''ll def keep this account a lot more updated in the future)' extension = '#LIES' newCaption = 'samCaption extension' %WRONG newCaptionCorrect = [samCaption ' ' extension] %% Casting % "Casting" is just a term that means changing a value from one data type % another. % char (changes ASCII value into character symbol) let = char(65); %produces A % double (changes character symbol into ASCII value) ascii = double('H');% produces 72 ('H' ascii value); % num2str (changes a number (double) into a char version of that number) num = 123; %length is 1 str = num2str(123) ; %'123' length is 3 % str2num (changes a char version of a number into a double version) str2 = '1234'; %length 4 num2 = str2num('1234'); %num2 is 1234 length 1 %%Question: %Note: the ASCII value for 'A' is 65 thing1 = char(65); %'A' thing2 = num2str(65); %'65' log = thing1 == thing2 %'A' == '65' --> [false false] 1 == [1 2] %% Math and Strings % Anytime you do math to a string, you get back an double (ASCII) value. %Produce the next letter from the given variable let = 'b'; nextLet = char(let+1) %Add enough question marks to the end of each string so that the overall %length is 1,000,000 hrideeCaption = 'whoever said watching anime makes you 93% less attractive was wrong'; questionLength1 = 1000000 - length(hrideeCaption) questionMarks1 = char(ones(1,questionLength1) * '?') newHrideeCaption = [hrideeCaption questionMarks1] shivamCaption = 'Haters said I''d lose the series. I said Shivam in four.' mariaCaption = 'who said blondes can't wear black boots' %https://www.instagram.com/hrideeculous/ %https://www.instagram.com/shivam_patel1/ %https://www.instagram.com/maria_cardelino/ %% Capitalize the entire string. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% str = 'this reminds me of patrick' %Functions: %upper %lower upperStr = upper(str) %three ways to capitalize capLet = str - 32 capLet2 = char(str - ('a' - 'A')) capLet3 = char(str - ' ') %this is actaully not correct because it is subtracting 32 from the spaces %too! Also, what if a letter is already capitalized, subtracting 32 from %that will cause problems! We will talk about how to deal with this later. %lowercasing bigLet = 'H'; littleLet = char(bigLet + 32); %It is super important to check your outputs with the 'isequal' function! %% Indexing Strings %https://www.instagram.com/mikey_hoff11/ mikeyCaption = 'Go dawgs amiright?'; %%Reverse revMikeyCaption = mikeyCaption(end:-1:1) %%All of the indexing we did with vectors of numbers still applies with %%strings. %% Indexing multiple spots %%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Capitalize a specific word in a string %strfind is useful %ind = strfind(str,pattern) mariaCaption = 'who said blondes can''t wear black boots' word = 'blondes' capWord = upper(word) ind = strfind(mariaCaption,word) %hardcoding mariaCaption(10:16) = capWord %slightly more generic mariaCaption(ind:16) = capWord %attempting to make more generic but WRONG mariaCaption(ind:length(word)) = capWord %attempting to make more generic but STILL WRONG mariaCaption(ind:ind + length(word)) = capWord %correct way mariaCaption(ind:ind+length(word)-1) = capWord %% More functions %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %sprintf %with sprintf i can use %s (strings),%d (doubles),%f(doubles and you can control decimal points) %to create spots to fill in later %str = sprintf(formattedStr,var1,var2,.....) %https://www.instagram.com/brohanthelegend/ hairRating = [6 8 9 5 10] avgRating = mean(hairRating) ratingStr = sprintf('Haircut Rating: %d',avgRating) ratingStr = sprintf('Haircut Rating: %0.1f',avgRating) name = 'Burhanuddin' age = 18 newRatingStr = sprintf('%s''s age is: %d, and their hair rating is %0.1f',name,age,avgRating) %strtok 1 time and multiple times str = 'MATLAB is bae'; [word1,rest] = strtok(str,' '); %without the second input, strtok assumes SPACE as the delimeter %word1 -> 'MATLAB', rest -> ' is bae' *STARTS WITH THE DELIMETER (a space)* [word2,rest] = strtok(rest); %word2 --> 'is' rest --> ' bae' %you can also have a LIST of delimeters [word,rest] = strtok(str,' Ta'); %this deliminates by space, T, OR a %word --> 'MA' rest --> 'TLAB is bae' %%sort function % suppose the string 'names' and 'ages' contain data about people. % Each index corresponds to a certain person, meaning the first spot in both % vectors corresponds to person 1. % Sort the names in descending order, then rearrange the ages to have % them align with the newly sorted name. names = 'HCD'; ages = [19 18 17]; [sortedNames inds] = sort(names) %sortedNames --> 'CDH' %inds = [2 3 1] sortedAges = ages(inds); %sortedAges --> [18 17 19] %% Example tracing and coding can be found in the class notebook. %% The link is in the class dropbox folder.

fliplr, flipud(arr)

- flip an array horizontally and vertically, respectively

Functions

A computer program is a series of instructions in order to accomplish the desired task. The process in which a task is completed is called an algorithm. This is nothing new to you. Humans develop and execute algorithms all of the time. If I asked you to make a bowl of cereal the order of your steps might be % 1) get a bowl % 2) get cereal % 3) get milk % 4) get spoon % 5) pour cereal into bowl % 6) pour milk into bowl However, these instructions are at a very high level. Each of the steps actually has many substeps that you need to complete, but often it is useful to use abstract (which is just another name for high level) steps to plan out an algorithm. When you are writing a computer program, you can't just leave instructions at an abstract level. You have to tell the computer exactly what you want to do at all steps. This is when you must start thinking about how to break down your thought process into more detailed and specific steps. Podcast Links %Last semester, I was recruited to be on a series of podcasts that talked %about computer science stuff. The first episode I did was about %algorithms! If you would like to listen, you can find the podcast here: %Spotify: %https://open.spotify.com/episode/0TDnUCHnF6FtjgP31SxLKd?si=fyEvgVp8RmOr2VLp3j87HQ&fbclid=IwAR0kT_m4PN87_cM_JJHbWS8UtpxeTVaGrsFDQGp7KBg5pI8U5kSgl7BjBgg %Apple podcasts: %https://podcasts.apple.com/us/podcast/algorithms-byte/id1042137974?i=1000449508429&fbclid=IwAR337GsBg3kCvsdpXLy-sAES_vLdfQHu4qOk8mj0m83cLI0EPBwSzRNDqeQ %The Raw Data Website: %https://www.rawdatapodcast.com/episodes/algorithms-byte-s1!500a2 %% Building Blocks of Computer Program Instructions %% Variables 11:25 % A variable is an entity that saves values during the execution of a % program. A variable's value can change throughout the program. % Variable names can NOT have special characters (except underscore) and % MUST start with a letter. %Valid variable names: kantwon, matlab_is_bae, wowz3rz93 %Invalid variable names: k@ntwon, matlab-is-bae, 93wowz3rz %% Data types % There are multiple data types you will learn. For now, all you have to % know is: % double: numbers % logical: true or false %% Assignment Operator % the assignment operator is the = symbol. Is is NOT the same thing as % "equals". The assignment operator executes the right hand side first and % then assigns the value to the left hand side. % example: luc = 18; JacK = true; sawyer = 20; luc = luc + 1; %value of luc is now 19 not 18, it has been overwritten JacK = luc; %JacK is now 19 Mathematical Operators These are similar to what you've probably used in math addition: + subtraction: - multiplication: .* division: ./ exponentiation: .^ NOT USING THE . BEFORE *,/,AND ^ IN THE FUTURE WILL CAUSE WEIRD THINGS TO HAPPEN. THEREFORE, GET IN THE HABIT OF ALWAYS USING IT NOW. WE WILL % EXPLAIN LATER WHAT IT DOES WITHOUT IT. %after these lines of code are run, what are the values of the variables: uno = 1 dos = 4 tres = 6 %num = 3 %num2 = 7 uno = 1; %1 dos = 2; %2 tres = uno + dos; %3 dos = 4; %4 num = tres; %3 num2 = tres + dos; %7 tres = tres + tres; %6 Logical Operators % Logical operators produce logical values. The ones you need to know are: % logical and: & % logical or: | (this is the symbol you get when you shift click the % backslash button) % logical equal: == % greater than or equal to: >= % less than or equal to: <= % greater than: > % less than: < % logical not equal: ~= % logical not: ~ % REFER TO logicalTable.png FOR A TABLE THAT SHOWS HOW THE AND AND OR OPERATORS WORK log1 = 1 == 2 %false %% What is a script % A script is just a collection of instructions that perform the same exact % operations every single time it is run. % The term "running a script" means telling matlab to execute all of the % lines of code in the script. This can be done by typing the name of the % name of the script into your command window % Let's create an example script called my_quad that performs the % quadractic equation fo r given values. %% look at script1.m %% look at script2.m for an improvement %% What is a function? % A function is a collection of instructions where given a certain set of % inputs produces a certain set of outputs. % This is nothing new. You've seen functions in math. For instance let's % say I had a math function that was defined as: % z(x,y) = x + y - 2*y % The function z takes in 2 inputs (x and y) and does some computations in % order to produce a certain output. % If my inputs were x = 2 and y = 4 % asking for z(2,4) would produce the answer 2 + 4 - 2*4 which is -2 %% Why do we LOVE functions? % Functions allow you to have lines of code that can always be executed but % for inputs that can change. You don't have to go into the function and % change any lines of code to get another output. All you have to do is % change the inputs. % There are two fundamental principles of functions: % 1) Abstraction %functions allow you to name a series of steps by name. You are taking %detailed steps and "abstracting" them to a higher level representation %which makes understanding them a lot easier. For instance, instead of %telling you to do all of the 6 individual steps to make a bowl of %certain, I can just say "make a bowl of cereal" and all of the steps %are "abstracted" into that statement. % 2) Encapsulation % The power of computer programming is being able to have many seperate % functions that don't necessarily interfere with one another. Functions % are black boxes that take inputs and produce outputs. Another % function can't change the commands or lines of code in another % function. All it can do is affect the inputs. We call this idea of % every function having all of its bits and pieces contained within % itself as "encapsulation". The commands are "encapsulated" within the % function. %% Function headers 11:17 % In order to define a function, we have to tell matlab a couple of things: % 1) It is a function (not a script) % 2) What do you want the function to output (if anything) % 3) Whats the name of the function % 4) What do you want the function to have as inputs (if anything) %These are the four parts of funciton headers. 2) and 4) are optional. Lets %go into the rules of each part. % 1) Dictating it is a funciton %first you have to use the word "function" to dictate that a it is a % function. It must be all lowercase and should turn blue. % 2) Outputs: % no outputs: don't put anything here. OR you could explicitly say you % have no outputs by writing [] = % 1 output: place the variable name of the output and then the % assignment operator. ex: myOutput = % You can also put square brackets around the output variable but it % not mandatory % ex: [myOutput] = % multiple outputs: place the variable names inside of square brackets % then the assignment operator. ex: [myOutput1 output2] = % THE BRACKETS ARE MANDATORY % including commas between outputs is OPTIONAL % ex: [myOutput1, output2] = % 3) Name of the function: % write the name of the function. function names follow the same rules % as varible names. % 4) Inputs: % no inputs: you can either put nothing, or explicitly say you have no % input by writing () % 1 input: place the variable name of your input inside of % parentheses. The parentheses are MANDATORY % ex: (in1) % multiple inputs: place the variable names of your inputs inside of % partheses and separate them by commas. the parentheses and the % commas are MANDATORY. % ex: (in1, blah) % The inputs and outputs dictated in the function header are known as % FORMAL PARAMETERS %So lets put it all together! %% Function header examples 11:25 % 1) A function called "boo" with 2 inputs, 2 outputs function [out1,out2] = boo(in1,in2) %valid function [out1 out2] = boo(in1,in2) %valid, comma in outputs arent mandatory function [out1 out2] = boo(in1 in2) %invalid, comma in inputs needed % 2) A function called hola no inputs 1 output function [out1] = hola() %valid function out1 = hola() %valid, dont need brackets on output function out1 = hola %valid, don't need to specify no inputs %% Is this a valid function header? 11:30 % 1) function in = blah(out) %Valid, just bad practice with naming variables % 2) Function out = hello(howdy) %invalid, capital F % 3) function [out1, out2] = randomThing(in1 in2) %not valid, no comma in inputs % 4) function out = myFunc(30) %no valid, invalid variable name for inputs % 5) function out %valid, this is a function with no inputs and no outputs %% Running functions 11:35 % You can run a function by typing into the command window the name of the % function, parentheses, and then the inputs. If you want the function to % a certain variable, you would assign this to said variable. %example: %root = sqrt(2341); %newNum = round(73.7); %when you have a function that has multiple outputs, you have to place %outputs in square brackets. If you only put one, then you will only get %back the first output. %[maxxNum,position] = max(3) %maxxNum --> 3 (the maximum number is the value 3) %position --> 1 (it is a list of 1 number so it is in the 1st spot) % When running a function, the inputs are known as ACTUAL PEREMETERS % running a function is very similar to writing a function header except % you dont include the word "function". However, when running a function, % you DON'T need to use the same variable names that were used in the % function header. We will talk about this later. %if you want to learn more about a built-in function you can access the %documentation of the function by typing either: %help nameOfFunction (this will print all of the documentation into your %command window) % or %doc nameOfFunction (this will open up a completely new window with the %documentation %% Steps for completing a drill problem on the homework 11:40 %-------------------------------------------------------------------------% %>>Step 1: Solve the problem as a human %Make sure you know how to solve the problem yourself...as a human. It %would be impossible for you to explain to someone (or in our case %something) else how to do a problem if you yourself don't know how to do %it! Therefore, pretend you are asked to do the problem yourself as a human %with the given instructions and input data. On paper, go through the steps %of actually solving the problem! %-------------------------------------------------------------------------% %>>Step 2: Break down your human thoughts into steps %After you are sure you know how to solve the problem yourself, start %breaking down your process into smaller steps. This is going to be tricky %at first because humans naturally combine a lot of things together and you %may not actually know all of the steps you're doing or WHY you are %actually doing them! But with practice, you will be able take your complex %thought process and break it down into small manageable steps. %In order to do this step, physically write out a SHORT description or %blurb about what you are trying to accomplish. %-------------------------------------------------------------------------% %>>Step 3: Translate your steps from human thoughts to Matlab %Given that you now have a roadmap of how you want to complete the %problem, step by step, translate each of the steps from "human-language" %to Matlab. %In order to do this step, you will have to start to learn the connections %between your own thinking and how to model that in Matlab. This requires %that you not only fully understand syntax and how to physically write %code, but you must UNDERSTAND the underlying principles of Matlab %operations. You only learn this through practice! Also, when hitting this step, multiple things may happen. A) You have no clue how to translate your step from human-language to Matlab if this is the case, this can be because of either lack of knowledge, or it's impossible to too complex to translate. If it is a lack of knowledge, this is when you need to either review lecture code, or get help. But many times, you won't know if it is a lack of knowledge or just too complex, and this is why it is important to ask for help when you're confused and to specifically ask WHY something works or WHY something doesn't work. If you are thinking of the problem in an unneccessarily complex way, then you may have to return to Step 1 or 2 and rethink how you can do the problem. This forces you to have to be able to thinking through a problem in MANY different ways. Over time, you will begin to learn more efficient ways of translating your human thinking to Matlab. You can easily translate the step %-------------------------------------------------------------------------Step 4: Check for syntax errors Ideally all of these steps have been done on paper and not in Matlab. So therefore, you should type what your wrote down on paper directly into Matlab and see if you have any syntax errors. This will allow you to star to see early on what type of things you get wrong when you don't have Matlab underlining syntax errors! %-------------------------------------------------------------------------% Step 5: Test your code Without Matlab, you should be able to go through your code BY HAND and trace it with a given input. You can also use Matlab to check to see if your outputs. If your code works, awesome. If not, return back to Step 1 or 2 and figure out what isn't working and WHY it isn't working. %-------------------------------------------------------------------------% VERY IMPORTANT! Throughout every step of the process, you should ALWAYS be asking yourself questions about generalizability and assumptions you're making. For instance, if you determine you should do a certain step, ask yourself: "Does this step (or series of steps) ALWAYS work?" "In which cases DOESN'T it works?" "What am I assuming about the data that I have at this point?" "Are these assumptions valid for the types of inputs my function can have?" Throughout the process, you should also be testing your code in small chunks. It might not seem like a big deal now, but when you start writing functions that are 50+ lines of code, it makes no sense to wait to test your code when youre done writing the whole thing. That will just make your life harder in trying to figure out what is right and what is wrong! Functions that may be helpful in HW01 round %how do you round to a different decimal? ceil floor abs cos sin cosd sind mod(in1,in2) %% Writing your own function 11:45 % Write a function called myQuad that takes in an A, B, and C value and % outputs the positive and negative roots. %% Function Scope % Every function has its own memory and realm that is lives in that is % different and unique. %% Tracing functions. % Tracing is just a term that means reading a function line-by-line and % determining what each line does and the overall function output. %The steps for tracing a function are: % 1) translate the actual parameters into the formal parameters of the % function. % 2) Execute all of the lines of code in the function % 3) translate the formal outputs to the actual outputs of whatever called the function %% Example 1: 11:55 % Given the following lines of code to be run into the command window, what % will be the values of out1, out2, and output1 in the command window workspace. A = 2; B = 3; [out1, out2] = mysteryFunction(A,B); %% Example 2: % look at mixup.pdf %% Example 3: %look at mysteryFunction2.pdf %% Example 4: % look at oldTest.pdf FOR ALL EXAMPLES, LOOK AT THE COURSE NOTEBOOK. IT IS ON THE DROPBOX LINK ON CANVAS %% Data Types and Switching Between Them %So far we have talked about 2 data types: double and logical. %Let's briefly introduct a new one: char % We denote chars with single quotes % ex: letter = 'a'; % How does MATLAB see chars? % Computers are run off of binary numbers (ones and zeros). So therefore, in memory you can't really store an actual symbol or letter. Instead, everything has to be converted into a number which then can ultimately be converted into binary. So, to Matlab, all chars are actually just numbers. The conversion is through what we call ASCII Values. % ASCII --> American Standard Code for Information Interchange % By looking up the ASCII table, we can see that when we type something % like a lowercase 'a', to the computer this is actually the value 97. Casting Now that we have 3 different data types, sometimes we might want to convert one type to another. This is called casting. Converting to logical logical function logical(1) --> true logical(0) --> false logical(5) --> true %anything other than 0 is true logical('a') --> true Converting to char %char function (only works for double --> char. NOT logical --> char) %looks up the value on the ASCII table char(65) --> 'A' char(49) -->'1' %Converting to double %double function double('K') --> 75 %this is the ASCII value of the char 'K' %doing math to a logical or a char by default changes it into a double 'a' + 1 --> 98 true + true + true --> 3 %ouch %% Changing case of chars %Often time you might have a char and want to change it to lowercase or %uppercase. Looking at the ASCII table, we can see that lowercase 'a' has a %value of 97, while capital 'A' has a value of 65. We can learn two things %from this: % 1) lowercase letters have higher ascii values than capital letter % 2) the difference between a lowercase letter and its corresponding % capital letter is 32. %Using both of these notions, suppose we have a varible 'var' that %contained a lowercase letter and we wanted to capitalize it. %One way of doing that to do math to the actual char: bigLet = char('a' - 32) bigLet = char('a' - ('a' - 'A')) Another way is to just use the upper/lower function bigLet = upper('a')

What is the difference between formal and actual parameters?

Formal parameters are variable names used in a function. Actual parameters are variables used when calling a function.

What is the advantage of using a function instead of a script?

Functions have the advantages of both abstraction and encapsulation while scripts do not. Abstraction: functions can accept different inputs, so the user doesn't need to know the complete details of how they work Encapsulation: functions have their own scope, reducing the clutter of the main workspace.

Explain the meaning of the statement "functions have their own scope."

Functions have variables that can't be accessed from command window or other functions; similarly, they cannot access variables defined elsewhere.

Define abstraction and encapsulation.

Abstraction is that even though you do not know how to write the code someone wrote, if you know how to use it, you can implement and utilize it in your function. For example, even though we might not know how to write mod function, but you can use mod function without really knowing how it works. Encapsulation is where each function has its own "scope" or "workspace."

Data Types

Data Types Intro: Data Types are simply a way to categorize different kinds of data. Many operations in Matlab (and functions that you create!) may only work for certain kinds of data. Data Types mean the same thing as classes. The three types we will be working with are double, char, and logical. Double: Doubles are simply any rational or irrational number, decimal, or integer value. Even pi is considered a type double in Matlab! num1 = 3; num2 = pi; Char: A Char is a character, symbol, or number. A series of chars is called a string. You must use single quotes to represent char values. To put an apostrophe in a string, use two single quotes: Var1 = 'you''re the best around' Var2 = 'nothings ever gonna keep you down!' Var3 = 'd' Computers, unfortunately, do not get the concept of character values, so it actually assigns it a number to keep track of it. This is called an ASCII value. There is a table with the ASCII values and corresponding character values, but you do not need to memorize anything for the exams. A common misconception is that you can simply add a char '5' to a double 5 and get a type double 10. What instead happens is that the char '5' gets converted to its ASCII value 53 and then is added to 5, resulting in type double 58 as the final answer. Matlab won't say that it's wrong, but it may not work as expected. Logicals: Logicals are simple true and false statements, and is often represented as 1 or 0 in Matlab. This data type is the result of using operators like > < >= <= ~= and ==. To assign logical values, you must actually type out true and false; typing 1 or 0 tells matlab that you have a type double 1 or 0. Log = true log2 = 17 > 38; %Log2 will be false because 17 < 38 Log3 = 2100 ~= 66; %Log3 will be true Converting to different data types:

In MATLAB, you right click a function you wrote that has one input and two outputs and press run. MATLAB throws an error that says "Not enough input arguments." What is the cause of this error?

Running the function through this method calls the function without any inputs.

What is encapsulation?

Variables defined in the function are known only to the function.

Vectors

What is a data structure % A data structure is an entity that can hold data. Throughout this class, we are going to learn about multiple data structures or ways to hold data. Each type of data structure has its own rules on: 1) what type of information can be contained 2) how the information is organized 3) how information can be added/created 4) how information can be accessed 5) how information can be deleted 6) what type of operations/manipulations you can do What is a vector? A vector is a basic data structure that is HOMOGENEOUS. This means that vectors can only contain data that is of the same class. Vectors have two main properties: 1) indicies 2) values An index is just a spot or location in a vector. In matlab, the first spot on the left is considered the index 1. Vectors grow from left to right. Creating Vectors %Vectors are denoted by square brackets []. There are 3 different ways to create vectors Direct Entry Method / Concatenation % You can just directly enter values inside of square brackets. What is happening is you are "concatenating" the values. Concatenation is just a fancy term for sticking stuff together. vec1 = [9 8 2 6 1] vector of numbers vec1b = [9,8,2,6,1] vector of numbers vec2 = [1 0 0 1 0]; vector of 1's and 0's vec3 = [true false false true false]; vector of logicals vec4 = ['h','e','l','l','o'];%vector of characters vec5 = 8;%technically a vector of 1 number vec5 = [8]; vec5 = [7;9;2];%vertical vector; vec6 = [vec1 vec2]%concatenating with other variable vec7 = [vec1 10 200 -5 6.7]%concatenating with other values vec8 = [-1 0 1 vec1]%can concatenate numbers in front length len = length(vec8) --> 8 %there are 8 values %% Colon Operator % Basic format: % startNumber: interval : stoppingNumber nums = 2:1:100;%2->100 evens2 = 2:2:8; %2->8 steps of 2 evens2b = 2:2:9; %also 2->8. Stopping number not guaranteed in the vector evens3 = 1:-1:10;%empty vector emptyVec = []; back = 100:-1:1%go backwards from 100 to 1 % Another format: % startNumber: stoppingNumber % THIS ASSUMES THAT THE INTERVAL IS 1 (positive 1) nums = 2:10; %2->10 nums2 = 300:1;% (300 can't go to 1 in steps of positive 1) %you can have variables in the colon operator too! a = 4 b = 5 c = 6 newVec = (a-2):(b/2):(c*a) %2:2.5:24 % ** THE STOPPING NUMBER IS NOT GUARANTEED TO BE IN THE VECTOR YOU CREATE %% Functions % zeros/ones % zeros(numberOfRows,numberOfColumns) z = zeros(1,10); %row vector of 10 zeros o = ones(5,1); %col vector of 5 ones % linspace % linspace(startingNumber, stoppingNumber, numberOfElements) linNums = linspace(5,70,12); linNumsDefault = linspace(2,5);% 100 evenly spaced values between 2 and 5 % rand(numRows, numCols) %% Indexing Vectors 11:15 % Accessing Single Value % Basic syntax: var = vec(index) instaLikes = []; A = ; % The second value of the vector is assigned to the variable A B = ;%Trying to index out of bounds sub = % subtract the 1st number from the 3rd number %what if sub = instaLikes() % %replacing % vec(index) = value instaLikes = [] ;%replace value in 3rd index with a value of 9 %after this, instaLikes is %copy the second value in the vector to the 3rd value in the vector %instaLikes --> ; %extend the vector to the 11th spot and place a 4 % Using "end" vec = []; last1 = ; last2 = ; last = ; %"end" translates to the number 4, vec(end) is the value 1 nextToLast = %end should be used only with indexing %vec = 2:2:end; %wrong and matlab tries to tell you %11:30 % Accessing Multiple Values vec = []; someNums = vec(); %[3 4 1] someNums = vec(); %WRONG indexing row, col, layers someNums = vec(); %using end in vec %change all of the numbers at odd indices to the last number vec = [4 9 4 0 4 3 4 5]; %hardcoding %generic/generalized %reversing ***************** ages = [] %empty vector %correct %%number of values being placed in has to equal number of spots vec= [8 1 0 2]; ; ;%e %11:40 %change all of the values at even indicies to the number that represents %their index. (the number at the 2nd index should be changed to 2, the %number at the 4th index should be changed to 4) vec = [2 5 9 1 0]; % --> [2 2 9 4 0] vec(2:2:end) = 2:2:length(vec)% vec([2,4]) = [2,4] vec(2:2:end) = 2:2:end % %vec(2:2:end) = 2:2:vec(end) %11:45 %%All of these are the same for this vector. Index every other value %%starting at the first vec = [3 4 5 1 7 9 10]; %[3 5 7 10] everyOther = ; %hardcoding everyOther2 = ; %colon everyOther3 = ; %colon no last everyOther4 = ; %most generic. can be used on any vector everyother5 = ; %using length %%%%% Slicing (indexing chunks) %Index the first half of a vector with an even number of values vec = [3 5 21 8 3 1 9 3] firstHalf = %Index the first half of a vector that isn't guaranteed to have an even %number of values vec = [3 5 21 8 3 1 9 3] firstHalf = %Index the second half of a vector with an even number of values vec = [3 5 21 8 3 1 9 3] secondHalf = ; % secondHalf = ;% %Index the second half of a vector that isn't guaranteed to have an even %number of values vec = [3 5 21 8 3 1 9 3 9] secondHalf = secondHalf = %11:50 Deleting %deleting a value in a vector is just inserting an empty vector into a position vec = [5 2 1] vec2 = [[] 2 1]% concatenating an empty bracket does nothing [2 1] %remove first value. after this the vector is just [2 1] %vec is now [2 1] %delete every other number vec = 1:3:10; %[1 4 7 10] vec(1:2:end) = []; %delete every other number starting at the first %after this vec --> [4 10] %% Vector Operations %11:55 % Mathematical % Using the dot before * or / means element by element operations. Without it, it will try to do matrix math. math1 = [2 3 4] .* 2; %I can use the dot or not with scalars. math2 = [2 3 4] * [3 4 1]; %Error because matrix dimensions dont agree for matrix multiplication. math2b = [2;3;4] * [3 4 1]; %this does matrix multiplication and you end up with a 3x3 matrix math3 = [2 3 4] .* [3 4 1]; % math3 --> [6 12 4] math4 = [2 3 4] .* [3 4]; %ERROR. Dimensions don't agree. % Logical % Dimensions have to be the same, or one of them has to be length 1. vec = [3 9 1 8]; log1 = vec > 3 % [false true false true] log2 = vec == [9 3 6 8]; % [false false false true] logERROR = vec == vec(2:end); %this is saying [3 9 1 8] == [9 1 8]. DIMENSION MISMATCH ERROR %determine if something is odd or even odd = mod(vec,2) == 1 %[1 1 1 0] == 1 --> [true true true false] even = mod(vec,2) == 0 %[false false false true] TALK ABOUT MOD Using Functions on Vectors vec = [2 4 1 9 32]; % length len = length(vec); %len --> 5 % sum/prod/mean mySum = sum(vec); %mySum --> 48 myProd = prod(vec); myMean = mean(vec); % max/min [maxx, ind] = max(vec); %% maxx --> 32, ind --> 5 suppose the vectors 'ages' and 'heights' contain data about people. Each index corresponds to a certain person, meaning the first spot in both vectors corresponds to person 1. Sort the ages in descending order, then rearrange the heights to have them align with the newly sorted ages. ages = [12 9 40 29 22]; heights = [120 100 180 155 160]; [sortedAges,inds] = sort(ages,'descend'); %sortedAges will be [9 12 22 29 40] %inds will be [2 1 5 4 3] sortedHeights = heights(inds); %omg what if i didn't know about descend sortedAges = sort(ages); revAge = sortedAges(end:-1:1); % all/any log = all(vec == 2); log2 = any(vec == 2);

fclose(fh)

closes a text file

cat(dimension, arr1, arr2, ...)

concatenates arrays in a particular dimension

cell2mat(arr)

converts a cell array of doubles to an array of doubles

cell(r,c)

creates a cell array of empty cells with dimensions r*c

cumsum(x,y)

estimates the area under a curve using rectangles

cumtrapz(x,y)

estimates the cumulative area under a curve using trapezoidal method

Function Name: cupcakeContestInputs: 1. (double) a vector of critics' scores for a cupcake flavor 2. (double) cutoff scoreOutputs:1. (double) vector of revised cupcake scores 2. (double) overall cupcake scoreFunction Description:Write a function called cupcakeContest that takes in a vector of scores for a cupcake flavor and returns the overall score of the flavor, as well as a vector of revised cupcake scores. To adjust for disgusting cupcakes, remove any cupcake score less than or equal to the second input. Return a vector of revised cupcake scores ordered from greatest to least. Take the average of the revised scores to return the overall cupcake score.

function[newScores, overall] = cupcakeContest(scores,cutoff) newScores = scores(scores>cutoff); overall = mean(newScores); newScores = sort(newScores,'descend'); end

open(filename, permission) -

opens a .txt file with specified permissions ('w', 'r', or 'a') and returns the file handle of the new file

fprintf(fh,line) -

prints a line to the text file specified by fh getfield

char(vec)

returns a string whose ASCII values are given by vec

imread(filename)-

returns a uint8 image array

fieldnames(sa)

returns all of the fields in a structure array as a column cell array

class(vec)

returns the data type of a variable

diff(vec)

returns the differences between adjacent entries in a vector

fgetl(fh), fgets(fh)

returns the next line down of the file specified by fh

find(vec)

returns the numerical indices where a logical vector is true

(struct, field) -

returns the value of a field in a structure

double(vec)

returns the values of vec as floating point numbers

all(vec)

returns true if all of the values in a logical vector are true

any(vec)

returns true if any of the values in a logical vector are true

floor(num) -

rounds a decimal down to the closest integer

ceil(num)

rounds a decimal up to the closest integer


Ensembles d'études connexes

Chapter 9 - Cozy Global Business

View Set

Digestive and Gastrointestinal Treatment Modalities

View Set

3, 4, 5, and 6, Times Tables (Combined)

View Set

TestOut Chapter 10 - Wireless Networking

View Set

DMV Written Test Question Bank (CA)

View Set

business ethics and social responsibility Ch 2

View Set

Pharmacology Made Easy 4.0 The Hematologic System

View Set