├── README.md ├── control ├── data_output4spreadsheet.txt ├── headache_data.txt ├── onramp_control.pdf ├── onramp_control_dataimport.m ├── onramp_control_for.m ├── onramp_control_if.m ├── onramp_control_try.m └── onramp_control_while.m ├── dataIO ├── amsterdam.bmp ├── data_written_from_matlab.txt ├── filename.csv ├── matlab.mat ├── my_matlab_variables.mat ├── onramp_dataIO.pdf ├── onramp_dataIO_copypaste.m ├── onramp_dataIO_export.m ├── test_datafile.txt ├── test_excelfile.xlsx └── testmat.mat ├── debugging ├── onramp_debugging.pdf ├── onramp_debugging_FIP.m ├── onramp_debugging_commonErrors.m └── onramp_debugging_profiler.m ├── desktop ├── onramp_desktop.pdf ├── onramp_desktop_calccolon.m └── onramp_desktop_exercises.m ├── scripts1 ├── basicstats.m ├── onramp_scripts1.pdf ├── onramp_scripts1_comments.m ├── onramp_scripts1_funInOut.m ├── onramp_scripts1_help.m ├── onramp_scripts1_path.m ├── onramp_scripts1_scripts.m └── onramp_scripts1_softcoding.m ├── scripts2 ├── anonfunc_exercise.m ├── onramp_functions.pdf ├── onramp_functions_anonfun.m ├── plotrandom.m └── uniquefx.m ├── variables ├── MATLAB_variables.pdf ├── onramp_variables.pdf ├── onramp_variables_indexing.m ├── onramp_variables_logicals.m ├── onramp_variables_naming.m ├── onramp_variables_numbers.m ├── onramp_variables_strings.m ├── onramp_variables_structures.m └── onramp_variables_whatAre.m └── visualize ├── amsterdam.bmp ├── colorful_pic.png ├── onramp_visualization_bars.m ├── onramp_visualization_exercises.m ├── onramp_visualization_figuresEtc.m ├── onramp_visualization_getset.m ├── onramp_visualization_imagescContour.m └── onramp_visualization_plotting.m /README.md: -------------------------------------------------------------------------------- 1 | # MATLAB onramp: coding, concepts, confidence, and style 2 | 3 | This repository contains all of the code, sample data files, and pdf readers corresponding to the course: 4 | https://www.udemy.com/course/matlab-programming-mxc/?couponCode=202304 5 | 6 | 7 | -------------------------------------------------------------------------------- /control/data_output4spreadsheet.txt: -------------------------------------------------------------------------------- 1 | Name trial choice rt accuracy 2 | billy 1 2 450 1 3 | bob 2 2 830 0 4 | -------------------------------------------------------------------------------- /control/headache_data.txt: -------------------------------------------------------------------------------- 1 | this is a text file with mixed strings and numbers. 2 | each row contains different information, some useful and some useless. 3 | we'll use matlab to read in each line separately, figure 4 | out whether to keep or trash that line, and extract the data we want. 5 | 6 | in this file, label-value data pairs are separated by tabs. it's the one 7 | useful thing we have to go on here. 8 | 9 | 10 | behavioral data begin on the following line 11 | trial 1 choice 2 rt 450 accuracy 1 12 | choice 2 trial 2 accuracy 0 rt 830 13 | well, i could go on and on, but you're starting to get the idea -------------------------------------------------------------------------------- /control/onramp_control.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/control/onramp_control.pdf -------------------------------------------------------------------------------- /control/onramp_control_dataimport.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Control statements 5 | % VIDEO: Application: Import-export data 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% advanced importing text data 11 | 12 | % Here we borrow from C language to flexibly read in mixed data. Let's say 13 | % you have some poorly organized behavioral data files to read in, but at 14 | % least you know what text strings to look for: 15 | 16 | fid = fopen('headache_data.txt','r'); 17 | % fid is a pointer to a location on the physical hard disk (similar to how 18 | % we used variables as handles to axes when plotting). The 'r' means read 19 | % (later we'll use 'w' for write). 20 | 21 | % In this particular example, we will extract the trial number, subject 22 | % choice, reaction time (RT), and accuracy for each trial. Fields are separated by tabs. 23 | 24 | mydata = []; % initialize... we can't initialize the full matrix, because we don't know how big this will be. 25 | 26 | % The following code will remain inside a loop, reading in and processing new 27 | % lines of data, until we reach the end of the file. 28 | row = 1; 29 | 30 | while ~feof(fid) % feof tests whether we're at the end of the file. 31 | 32 | aline = fgetl(fid); % read a line ("file get line") 33 | 34 | aline = regexp(aline,'\t','split'); 35 | % regexp can be used to cut data according to delimiters. Here we will 36 | % cut this string of characters into a cell array in which elements of 37 | % the array are separated by tabs. 38 | 39 | % here we use strcmpi to compare strings. The "i" means to ignore case. 40 | if ~any(strcmpi('trial',aline)) 41 | continue % continue means to skip to the next iteration of the loop. 42 | end 43 | 44 | trial_column = find(strcmpi('trial', aline)); 45 | choice_column = find(strcmpi('choice', aline)); 46 | rt_column = find(strcmpi('rt', aline)); 47 | accuracy_column = find(strcmpi('accuracy',aline)); 48 | 49 | mydata(row,1) = str2double(aline{trial_column+1}); % Note that we didn't initialize the size of the variable "behavioral_data" so matlab gives a warning. 50 | mydata(row,2) = str2double(aline{choice_column+1}); % If the variable is relatively small, it doesn't matter. 51 | mydata(row,3) = str2double(aline{rt_column+1}); % If the variable is large, however, it's best to initialize it to something really big, and then cut it down to size afterwards. 52 | mydata(row,4) = str2double(aline{accuracy_column+1}); 53 | 54 | row = row+1; % increment row 55 | end 56 | 57 | fclose(fid); % don't forget to close the file after you finish it 58 | 59 | %% advanced writing out data 60 | 61 | fid = fopen('data_output4spreadsheet.txt','w'); 62 | 63 | % we want the first row to be variable labels, then rows of mixed string-number data 64 | 65 | % variable labels 66 | variable_labels = {'Name';'trial';'choice';'rt';'accuracy'}; 67 | 68 | % let's add subject names 69 | subject_names = {'billy';'bob'}; 70 | 71 | % write out header row 72 | for vari=1:length(variable_labels) 73 | fprintf(fid,'%s\t',variable_labels{vari}); 74 | % the %s is for string; %g is for number. 75 | end 76 | 77 | % insert a new-line character 78 | fprintf(fid,'\n'); 79 | 80 | for datarowi=1:size(mydata,1) 81 | 82 | % print subject name 83 | fprintf(fid,'%s\t',subject_names{datarowi}); 84 | 85 | % now loop through columns (variables) 86 | for coli=1:size(mydata,2) 87 | fprintf(fid,'%g\t',mydata(datarowi,coli)); 88 | end 89 | fprintf(fid,'\n'); % end-of-line 90 | 91 | % You could also do this in one line: 92 | %fprintf(fid,'%s\t%g\t%g\t%g\t%g\n',subject_names{datarowi},behavioral_data(datarowi,1),behavioral_data(datarowi,2),behavioral_data(datarowi,3),behavioral_data(datarowi,4)); 93 | 94 | fprintf('Finished writing line %g of %g\n',datarowi,size(mydata,1)); 95 | end 96 | 97 | fclose(fid); 98 | 99 | % Note that if you omit the first argument to fprintf, it puts the output 100 | % in the command instead of the text file, as in the final line of this for-loop. 101 | 102 | 103 | %% done. 104 | -------------------------------------------------------------------------------- /control/onramp_control_for.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Control statements 5 | % VIDEO: For-loops 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% for-loops 11 | 12 | % A for-loop is a way to iterate repeatedly: 13 | 14 | for counting_variable = 1:10 15 | disp(counting_variable); % disp stands for display, which prints information in the command window 16 | end 17 | 18 | %% another example: 19 | 20 | for i = 1:2:10 21 | disp([ 'The ' num2str(i) 'th iteration value times 2 divided by 3 and added to 7 is ' num2str((i*2)/3+7) '.' ]) 22 | end 23 | 24 | 25 | %% 26 | % an if-statement embedded in a loop 27 | for numi=1:10 28 | if mod(numi,2)==0 29 | disp([ 'The number ' num2str(numi) ' is even.' ]) 30 | else 31 | disp([ 'The number ' num2str(numi) ' is odd. And that''s the way the news goes.' ]) 32 | end 33 | end 34 | 35 | 36 | % You can embed loops within loops 37 | for i = 1:5 38 | for j = 3:7 39 | product_matrix(i,j) = i*j; % Matlab produces a warning here because product_matrix is not initialized. 40 | end 41 | end 42 | % Two important things to note about the example above: (1) You can use the same numbers as 43 | % indices AND as variables; (2) Unspecified elements in a matrix are 44 | % automatically created and set to zero. 45 | 46 | 47 | 48 | number_rows = 5; % having many spaces is allowed and facilitates code aesthetics 49 | number_columns = 7; 50 | 51 | % initialize matrix with zeros 52 | product_matrix = zeros(number_rows,number_columns); 53 | 54 | for i=1:number_rows 55 | for j=1:number_columns 56 | product_matrix(i,j)=i*j; 57 | end % end j-loop 58 | end % end i-loop 59 | % note the comments following end-statements. When you have multiple long 60 | % loops, this kind of commenting will be helpful. Also note that when you 61 | % click on one of the "for" or "end" statements, its pair will be underlined. 62 | 63 | 64 | 65 | % a common problem in for loops: 66 | avec = zeros(7,1); 67 | for i=-3:3 68 | avec(i) = i; 69 | end 70 | 71 | 72 | 73 | %% done. 74 | -------------------------------------------------------------------------------- /control/onramp_control_if.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Control statements 5 | % VIDEO: Control statement architecture; if and switch 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% if-statements 11 | 12 | % Exactly how it sounds 13 | if 4>5 14 | disp('Something has gone awry in the universe') 15 | end 16 | 17 | 18 | % with an alternative 19 | if 4>5 20 | disp('Something is still very wrong') 21 | else 22 | disp('Whew! Everything''s normal.') % note the two single-quote marks inside the string 23 | end 24 | 25 | 26 | % more alternatives 27 | randnum = randn; 28 | if randnum>2 29 | disp('Big number') 30 | elseif randnum>0 && randnum<2 31 | disp('Not so big') 32 | elseif randnum<0 && randnum>-2 33 | disp('A bit on the negative side') 34 | else 35 | disp('super negative') 36 | end 37 | 38 | 39 | %% switch 40 | 41 | % the 'switch/case' statement is similar to 'if/else' 42 | animal = 'monkey'; 43 | 44 | 45 | switch animal 46 | case 'dog' % compares variable "animal" to 'dog' 47 | fav_food = 'cheese'; 48 | case 'cat' 49 | fav_food = 'bird-flavored yogurt'; 50 | case 'monkey' 51 | fav_food = 'bananas'; 52 | otherwise 53 | fav_food = 'pizza'; 54 | end % end switch 55 | 56 | disp([ 'In the wild, the ' animal ' prefers to eat ' fav_food '.' ]) 57 | 58 | 59 | %% done. 60 | 61 | -------------------------------------------------------------------------------- /control/onramp_control_try.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Control statements 5 | % VIDEO: Try-catch 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% try-catch 11 | 12 | % used to ignore errors but collect information about the error for later inspection 13 | 14 | vec = [2 3 4]; 15 | 16 | % case 1: 17 | vec(4) 18 | 19 | % case 2: 20 | try 21 | vec(4) 22 | catch me 23 | end 24 | 25 | 26 | %% done. 27 | -------------------------------------------------------------------------------- /control/onramp_control_while.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Control statements 5 | % VIDEO: While-loops 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% while-loops 11 | 12 | % while loops are similar to for-loops except: 13 | % 1) You don't need to specify before-hand how many iterations to run, 14 | % 2) The looping variable is not implicitly updated; you have to increment it yourself. 15 | 16 | toggle = false; 17 | 18 | idx = 1; 19 | while toggle 20 | disp([ 'I''m working on step ' num2str(idx) ' and it makes me happy.' ]) 21 | end 22 | 23 | %% example of while loop 24 | 25 | % initialize values to 100 26 | [curr_val,init_val] = deal( 100 ); 27 | 28 | toggle = true; 29 | 30 | while toggle 31 | 32 | % decrease value by 5% 33 | curr_val = curr_val * .95; 34 | 35 | % compute percent change from initial value 36 | pctchng = 100*(init_val-curr_val) / init_val; 37 | 38 | % round to 2 decimal points 39 | pctchngRound = round(pctchng*100)/100; 40 | 41 | % display message 42 | disp([ 'Value = ' num2str(curr_val) ', ' num2str(pctchngRound) '% change from original value.' ]) 43 | 44 | % check if toggle should be switched off 45 | if curr_val<1 46 | toggle = false; 47 | end 48 | end 49 | 50 | 51 | 52 | %% done. 53 | -------------------------------------------------------------------------------- /dataIO/amsterdam.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/dataIO/amsterdam.bmp -------------------------------------------------------------------------------- /dataIO/data_written_from_matlab.txt: -------------------------------------------------------------------------------- 1 | 1.6894 -1.0752 2 | 1.2823 -0.090967 3 | -0.58263 -0.25277 4 | 0.22261 1.1948 5 | 0.77945 0.60606 6 | 0.38471 0.54051 7 | 0.69637 -1.4449 8 | -0.11272 -0.96769 9 | -0.038824 0.20205 10 | 0.088089 -0.34788 11 | -0.78966 1.2901 12 | 1.423 1.3412 13 | 0.0063317 -0.5808 14 | 0.68648 0.87514 15 | -0.85493 1.3954 16 | -------------------------------------------------------------------------------- /dataIO/filename.csv: -------------------------------------------------------------------------------- 1 | 15,18,16,21,22 2 | 22,14,13,21,23 3 | 24,1,9,9,17 4 | 14,11,23,15,5 5 | -------------------------------------------------------------------------------- /dataIO/matlab.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/dataIO/matlab.mat -------------------------------------------------------------------------------- /dataIO/my_matlab_variables.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/dataIO/my_matlab_variables.mat -------------------------------------------------------------------------------- /dataIO/onramp_dataIO.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/dataIO/onramp_dataIO.pdf -------------------------------------------------------------------------------- /dataIO/onramp_dataIO_copypaste.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Getting data into and out of MATLAB 5 | % VIDEO: Copy-paste, MATLAB files, Excel, and image files 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% copy/paste from text file or spreadsheet 12 | 13 | % Hint: use square brackets for numbers. 14 | dat = [ 15 | ]; 16 | 17 | %% importing "nice" text data 18 | 19 | % The simplest way to read in text data is if all data in the next are 20 | % numbers (no text). Open a text editor and make a small matrix (say, 3x4). 21 | % Next, type: 22 | data = load('test_datafile.txt'); 23 | 24 | % slightly more advanced: 25 | [file_name,file_path] = uigetfile('*.txt'); % ui = user-interface 26 | data = load([ file_path file_name ]); 27 | 28 | % variable name is file name 29 | whos 30 | load('test_datafile.txt'); 31 | whos 32 | 33 | %% MATLAB-format .mat files 34 | 35 | % load directly into the workspace 36 | clear 37 | load('testmat.mat') 38 | % or 39 | load testmat 40 | whos 41 | 42 | 43 | % or load as fields into a structure 44 | clear 45 | data = load('testmat.mat'); 46 | whos 47 | 48 | %% excel files 49 | 50 | % you can also read in data from excel files, but BE CAREFUL because this 51 | % function can act in unexpected ways, e.g., by removing empty columns and 52 | % rows without warning (this can be seen in comparing "numberdata" to "raw_data"). 53 | % Therefore, it might be best to use the "raw" data output. 54 | [numberdata,textdata,raw_data] = xlsread('test_excelfile.xlsx'); 55 | 56 | %% reading pictures 57 | 58 | amsterpic = imread('amsterdam.bmp'); 59 | 60 | 61 | %% done. 62 | -------------------------------------------------------------------------------- /dataIO/onramp_dataIO_export.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Getting data into and out of MATLAB 5 | % VIDEO: Exporting data in MATLAB, text, and Excel formats 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% MATLAB format 12 | 13 | % save as a .mat file: 14 | save('my_matlab_variables.mat','data','amsterdam','x'); % Question: Why does matlab crash on this line? 15 | 16 | % possible but not recommended 17 | save % saves the entire workspace in matlab.mat 18 | 19 | 20 | %% simple text export 21 | 22 | % The function 'dlmwrite' is useful if you have a matrix of numbers 23 | % and want to write a text file of only numbers: 24 | dlmwrite('data_written_from_matlab.txt',data,'\t'); 25 | % the final argument is the delimieter. This can be tab (\t), space ( ), comma (,), the letter X (X), etc. 26 | 27 | 28 | %% Excel format 29 | 30 | % export as Excel file 31 | mat2save = round( 25*rand(4,5) ); 32 | 33 | % this function won't work if MATLAB cannot connect to a Microsoft Excel 34 | % server, which happens if you don't have Microsoft Office. 35 | xlswrite('filename.xlsx',mat2save) 36 | 37 | 38 | %% csv (comma-separated-values) 39 | 40 | csvwrite('filename.csv',mat2save) 41 | 42 | 43 | %% done. 44 | -------------------------------------------------------------------------------- /dataIO/test_datafile.txt: -------------------------------------------------------------------------------- 1 | 1 3 2 4 2 | 5 7 6 3 3 | 9 5 3 8 -------------------------------------------------------------------------------- /dataIO/test_excelfile.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/dataIO/test_excelfile.xlsx -------------------------------------------------------------------------------- /dataIO/testmat.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/dataIO/testmat.mat -------------------------------------------------------------------------------- /debugging/onramp_debugging.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/debugging/onramp_debugging.pdf -------------------------------------------------------------------------------- /debugging/onramp_debugging_FIP.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Debugging 5 | % VIDEO: The FIP (find, inspect, plot) debugging strategy 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% how to debug 11 | 12 | % 1) (F)ind the offending line and piece of code 13 | % 2) (I)nspect error message and variables (check sizes!) 14 | % 3) (P)lot (or image, or bar, or whatever is appropriate) 15 | % 4) Fix or change 16 | % 5) Learn a lesson! 17 | 18 | % generate random phase values 19 | N = 100; 20 | phases = 2*pi*rand(N,1); 21 | 22 | % initialize 23 | meanvecL = zeros(N); 24 | 25 | % loop over time points 26 | for sampi=1:N 27 | 28 | % pick random points to sample 29 | pnts2sample = round( sampi*rand(sampi,1) ); 30 | 31 | % compute mean vector length 32 | meanvecL(sampi) = abs(mean(exp(1i*phases(pnts2sample)))); 33 | end 34 | 35 | % plot the results 36 | figure(1), clf 37 | plot(1:N,meanvecL,'s-','linew',2,'markersize',10,'markerfacecolor','k') 38 | 39 | 40 | %% done. 41 | -------------------------------------------------------------------------------- /debugging/onramp_debugging_commonErrors.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Debugging 5 | % VIDEO: Examples of common programming errors 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% types of errors: 12 | 13 | % misspelled variables 14 | variable = 10; 15 | variabel 16 | 17 | 18 | % incomplete lines of code 19 | for i= 20 | disp(i) 21 | end 22 | 23 | 24 | % invalid indexing 25 | n = 12; 26 | datavec = linspace(1,50,n) .* rand(1,n); 27 | for i=1:15 28 | newvec(i) = datavec(i)^2 * sign(randn); 29 | end 30 | 31 | 32 | % dimension mismatch 33 | dat1 = randn(30,3); 34 | dat1(1:10,1:2) = zeros(10,3); 35 | 36 | 37 | % incorrect function inputs/outputs 38 | mat1 = randn(100); 39 | imagesc(1:100,mat1) 40 | 41 | 42 | %% The worst, most dangerous, and hardest to find bugs... 43 | 44 | % just some loop with i as looping index 45 | n = 4; 46 | d = zeros(n,1); 47 | for i=1:n 48 | d(i) = i^2 - log(i); 49 | end 50 | 51 | % create complex sine wave 52 | fs = 1000; 53 | t = -2:1/fs:2; 54 | s1 = exp(2*i*pi*t); 55 | 56 | %{ 57 | figure(1), clf 58 | subplot(211) 59 | plot(t,real(s1),'linew',3) 60 | xlabel('Time (s)'), ylabel('Amplitude') 61 | title('First try (wrong!)') 62 | 63 | % i should be sqrt(-1) 64 | clear i 65 | s2 = exp(2*i*pi*t); 66 | % hint: better would be to use 1i instead of i 67 | s2 = exp(2*1i*pi*t); 68 | 69 | subplot(212) 70 | plot(t,real(s2),'linew',3) 71 | xlabel('Time (s)'), ylabel('Amplitude') 72 | title('Corrected') 73 | %} 74 | 75 | %% two additional examples 76 | 77 | % intention is to do element-wise multiplication 78 | n = 12; 79 | datavec = linspace(1,50,n) .* rand(n,1); 80 | % The above line is version-dependent: 81 | % MATLAB 2016 and earlier will give an error. 82 | % MATLAB 2017 will produce the outer product. 83 | % Both versions give the "wrong" result, though. 84 | 85 | 86 | 87 | % awkward matrix indexing 88 | randmat = randn(5,4,7,2,5,7); 89 | 90 | % legal but difficult to interpret (use sub2ind): 91 | randmat(7000) 92 | 93 | % legal but a terrible idea 94 | randmat(2,4,2,2:57) 95 | 96 | % best approach (N-D matrix, N-1 commas!): 97 | randmat(1,3,6,2,2,3) 98 | 99 | 100 | %% done. 101 | -------------------------------------------------------------------------------- /debugging/onramp_debugging_profiler.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Debugging 5 | % VIDEO: tic/toc, MATLAB profiler 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% using tic/toc to time code 12 | 13 | % brief intro to tic/toc 14 | tic 15 | pause(1) 16 | toc 17 | 18 | % good practice to run several times 19 | data = randn(100000,1); 20 | tic, fft(data); toc % MATLAB initializes fft on first run 21 | tic, fft(data); toc % now should be faster 22 | 23 | %% using tic/toc to show the importance of initialization 24 | 25 | clear 26 | n = 3000; 27 | 28 | % no initialization 29 | tic 30 | for i=1:n 31 | amat1(i,i) = i; 32 | end 33 | t(1) = toc; 34 | 35 | 36 | % with initialization 37 | tic 38 | amat2 = zeros(n); 39 | for i=1:n 40 | amat2(i,i) = i; 41 | end 42 | t(2) = toc; 43 | 44 | 45 | % better?: 46 | tic 47 | amat3 = diag(1:n); 48 | t(3) = toc; 49 | 50 | 51 | % now plot the computation times 52 | bar(t) 53 | set(gca,'xtick',1:3,'xticklabel',{'No init';'init';'diag'}) 54 | ylabel('Computation time (sec.)') 55 | title('Computation times to achieve the same result.') 56 | 57 | %% MATLAB profiler 58 | 59 | % Put the code below into a separate file (e.g., tmpscript) and run 60 | profile on 61 | tmpscript; 62 | profile viewer; 63 | % Then inspect the profiler results and 64 | % think about ways to improve the code. 65 | 66 | 67 | 68 | % number of elements 69 | N = 1000; 70 | 71 | % initialize 72 | data = randn(10,N) ; 73 | result = zeros(N); 74 | 75 | for i=1:100 76 | 77 | clear ls1 78 | for j=1:N 79 | ls1(j,j) = i + j/N; 80 | end 81 | 82 | % make a nice gradient 83 | ls1 = transpose(ls1); 84 | ls2 = ls1*ls1'; 85 | 86 | dataX = abs( fft(data) ) + randn(size(data)); 87 | 88 | result = result + ls2*rand + dataX'*dataX; 89 | end 90 | 91 | 92 | %% end. 93 | -------------------------------------------------------------------------------- /desktop/onramp_desktop.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/desktop/onramp_desktop.pdf -------------------------------------------------------------------------------- /desktop/onramp_desktop_calccolon.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: MATLAB desktop 5 | % VIDEO: MATLAB as a calculator, colon operator 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% MATLAB as a calculator 11 | 12 | % copy/paste the code into the command window to evaluate 13 | 1+1 14 | 15 | % spacing can improve code readability 16 | 4*5+8 17 | 4 * 5 + 8 18 | 4*5 + 8 19 | 20 | % parentheses also improve code readability 21 | 5*3/6^2 22 | (5*3) / (6^2) 23 | 24 | % parentheses can also override order-of-operations 25 | 3^2.3+4.1 26 | 3^(2.3+4.1) 27 | 28 | 29 | 30 | %% The colon operator 31 | 32 | % basic use 33 | 1:5 34 | 7:109 35 | -15:4 36 | 37 | % non-default skipping 38 | 1:.5:5 39 | 40 | % count backwards 41 | 10:1 42 | 43 | % MATLAB stays within the boundaries 44 | 1:5:10 45 | 46 | 47 | 48 | %% end. 49 | -------------------------------------------------------------------------------- /desktop/onramp_desktop_exercises.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: MATLAB desktop 5 | % VIDEO: Solve some MATLAB exercises! 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% Exercise 1 11 | 12 | % Generate a sequence of odd numbers. 13 | % For each element, add 5 and divide by 2. 14 | % Repeat for a sequence of even numbers. 15 | 16 | 17 | 18 | %% Exercise 2 19 | 20 | % delete as many parentheses as possible without changing the results! 21 | ((9/3)+(4/2))^(( (2)+sqrt(9) )) 22 | 23 | 24 | %% Exercise 3 25 | 26 | % convert the sequence [2 4 6] into [-1 0 1] 27 | 2:2:6 28 | 29 | 30 | % convert the sequence [-1 0 1] into [10 100 1000] 31 | -1:1 32 | 33 | 34 | % convert the sequence 1:9 into [1 1 1 2 2 2 3 3 3] 35 | 1:9 36 | 37 | 38 | 39 | %% done. 40 | -------------------------------------------------------------------------------- /scripts1/basicstats.m: -------------------------------------------------------------------------------- 1 | function stats = basicstats(invar) 2 | % stats = basicstats(invar) 3 | % 4 | % This function computers the mean, sum, and standard deviation of an input numeric vector. 5 | % 6 | % INPUT: invar - input vector, must be numeric at least 3 elements long. 7 | % 8 | % OUTPUT: stats - a 3-element vector containing [ mean sum stdev ] 9 | % 10 | % written by mikexcohen.com 11 | % 12 | 13 | %% input checks 14 | 15 | % check that the input is numeric 16 | if ~isnumeric(invar) 17 | help basicstats 18 | error('Input must be numeric!') 19 | end 20 | 21 | % input has at least 3 numbers 22 | if numel(invar)<3 23 | help basicstats 24 | error('Input must contain at least 3 numbers!') 25 | end 26 | 27 | % must be a vector, not a matrix 28 | if ~isvector(invar)%sum(size(invar)~=1)>1 29 | error('Only vector inputs, not matrix inputs!') 30 | end 31 | 32 | %% compute the basic statistics 33 | 34 | % compute the mean 35 | themean = mean(invar); 36 | 37 | % compute the sum 38 | thesum = sum(invar); 39 | 40 | % compute the standard deviation 41 | thestdev = std(invar); 42 | 43 | %% display the results to the command window 44 | 45 | clc 46 | disp([ 'The mean of the input is ' num2str(themean) '.' ]) 47 | disp([ 'The sum of the input is ' num2str(thesum) '.' ]) 48 | disp([ 'The standard deviation of the input is ' num2str(thestdev) '.' ]) 49 | 50 | %% prepare the output 51 | 52 | stats = [ themean thesum thestdev ]; 53 | 54 | -------------------------------------------------------------------------------- /scripts1/onramp_scripts1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/scripts1/onramp_scripts1.pdf -------------------------------------------------------------------------------- /scripts1/onramp_scripts1_comments.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Scripts and functions, part 1 5 | % VIDEO: Comments, cells, spacing 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% comments and cells 12 | 13 | % A comment is text that is ignored by MATLAB 14 | % and is used to annotate and explain code. 15 | 16 | q = 7; % comments on same line as code 17 | 18 | %{ 19 | A block of lines, 20 | all commented. 21 | %} 22 | 23 | %% cells 24 | 25 | % Press Ctrl-Enter to run the entire cell. 26 | x = 1; 27 | 28 | disp([ 'Running this cell to print the number ' num2str(x) ]) 29 | 30 | %% Spacing 31 | 32 | % spacing is often unnecessary but always useful. Consider: 33 | ans1=4*5+3/4-13^5; 34 | ans2 = 4*5 + 3/4 - 13^5; 35 | 36 | % spacing for assignments and control statements as well: 37 | v=9; 38 | for vi=1:v 39 | result1(vi)=vi^v-4+3/vi^2;end 40 | 41 | % or: 42 | v = 9; 43 | result2 = zeros(v,1); 44 | for vi = 1:v 45 | result2(vi) = vi^v - 4 + 3/(vi^2); 46 | end 47 | 48 | 49 | %% done. 50 | -------------------------------------------------------------------------------- /scripts1/onramp_scripts1_funInOut.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Scripts and functions, part 1 5 | % VIDEO: Function inputs and outputs 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% basic function usage 12 | 13 | % functions take inputs in parentheses 14 | vect = [ 1 2 3 ]; 15 | sum(vect) 16 | % or 17 | sum([ 1 2 3 ]) 18 | 19 | % function outputs stored as variables 20 | numsum = sum([ 1 2 3 ]); 21 | 22 | 23 | % some functions take multiple inputs 24 | linspace(1,3,5) 25 | 26 | % some functions take multiple outputs 27 | [ maxval,maxidx ] = max([1 4 2 2]) 28 | 29 | %% functions for determining the size of variables 30 | 31 | % create a matrix of random numbers 32 | randmat = randn(30,4,10); 33 | randvec = randn(20,1); % a matrix, not a vector! 34 | 35 | % size 36 | size(randmat) 37 | size(randmat,2) 38 | 39 | % length 40 | length(randvec) 41 | length(randmat) 42 | 43 | % numel 44 | numel(randvec) 45 | numel(randmat) 46 | 47 | 48 | %% done. 49 | 50 | -------------------------------------------------------------------------------- /scripts1/onramp_scripts1_help.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Scripts and functions, part 1 5 | % VIDEO: Getting help on functions 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% information about function usage 11 | 12 | % nearly all functions have help files 13 | help fft 14 | 15 | % sometimes more detailed help from doc 16 | doc fft 17 | 18 | %% using test code from the help doc 19 | 20 | % notice the sample code at the bottom of the help doc 21 | help plot3 22 | 23 | %% open a file to see the help text at the top 24 | 25 | edit plot3 26 | 27 | %% done. 28 | 29 | -------------------------------------------------------------------------------- /scripts1/onramp_scripts1_path.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Scripts and functions, part 1 5 | % VIDEO: The MATLAB path 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% demo. 12 | 13 | 14 | %% adding one folder to the path 15 | 16 | addpath('C:\Users\mxc\Dropbox\classes\udemy\onramp\scripts1\') 17 | 18 | 19 | %% adding all subfolders to the path 20 | 21 | addpath( genpath('C:\Users\mxc\Dropbox\classes\udemy\onramp\' )) 22 | 23 | 24 | %% done. 25 | -------------------------------------------------------------------------------- /scripts1/onramp_scripts1_scripts.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Scripts and functions, part 1 5 | % VIDEO: Scripts vs. functions, organization 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | 12 | %% evaluating code in a script 13 | 14 | y = 5; 15 | 16 | 17 | %% viewing functions 18 | 19 | % most functions are also viewable, e.g. 20 | edit linspace 21 | 22 | % some are compiled 23 | edit sum 24 | 25 | 26 | %% done. 27 | 28 | -------------------------------------------------------------------------------- /scripts1/onramp_scripts1_softcoding.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Scripts and functions, part 1 5 | % VIDEO: Parameters, hard-coding vs. soft-coding 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% soft-coding 12 | 13 | % parameters and toggles listed at the top of the script: 14 | param = 4.2; 15 | 16 | % ... hundreds of lines of code ... 17 | dataResult = tempresult * param; 18 | % ... more hundreds of lines of code ... 19 | otherresult = tempresult * param; 20 | 21 | 22 | %% hard-coding 23 | 24 | % ... hundreds of lines of code ... 25 | dataResult = tempresult * 4.2; 26 | % ... more hundreds of lines of code ... 27 | otherresult = tempresult * 4.2; 28 | 29 | 30 | %% done. 31 | -------------------------------------------------------------------------------- /scripts2/anonfunc_exercise.m: -------------------------------------------------------------------------------- 1 | 2 | funxy = @(s,t) 2.*s - sqrt(s).*t.^2; % confirm: fine with x,y 3 | 4 | x = linspace(0,5,100); 5 | y = linspace(-3,3,200); 6 | 7 | result = zeros(length(x),length(y)); 8 | 9 | for xi=1:length(x) 10 | % result(xi,:) = funxy(x(xi),y); 11 | for yi=1:length(y) 12 | result(xi,yi) = funxy(x(xi),y(yi)); 13 | end 14 | end 15 | 16 | [Y,X] = meshgrid(y,x); 17 | result = funxy(X,Y); 18 | 19 | clf 20 | contourf(x,y,result',40,'linecolor','none') 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /scripts2/onramp_functions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/scripts2/onramp_functions.pdf -------------------------------------------------------------------------------- /scripts2/onramp_functions_anonfun.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Functions, part 2 5 | % VIDEO: Anonymous functions 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | 12 | %% a simple anonymous function 13 | 14 | % define function: 15 | % name = @(input) function; 16 | 17 | % example: 18 | myfunc = @(x) x^2; 19 | 20 | % a different class of variable: 21 | whos 22 | myfunc 23 | 24 | % a better function name: 25 | x2fun = @(x) x^2; 26 | 27 | 28 | % test that it works when you know the answer 29 | x2fun(0) 30 | x2fun(2) 31 | x2fun(4) 32 | 33 | % does it work on vector inputs? 34 | x2fun(1:3) 35 | 36 | 37 | % embed directly into plot function 38 | x = linspace(-3,3,100); 39 | plot(x,x2fun(x),'s-') 40 | 41 | % can also save outputs as new variable 42 | y = x2fun(x); 43 | 44 | %% multiple inputs 45 | 46 | % good function name with multiple inputs 47 | xSquaredWoffset = @(x,y) x.^2 + y; 48 | 49 | % always test with known outputs first! 50 | xSquaredWoffset(3,0) 51 | 52 | 53 | % 2D inputs to sample the parameter space 54 | x = linspace(-3,3,50); 55 | [X,Y] = meshgrid(x); 56 | 57 | % evaluate the function for both variables 58 | Z = xSquaredWoffset(X,Y); 59 | 60 | % make an image 61 | imagesc(x,x,Z) 62 | xlabel('X') 63 | ylabel('Y (offset)') 64 | title([ 'Function: ' func2str(xSquaredWoffset) ]) 65 | 66 | 67 | % or plot. 68 | plot(x,Z) 69 | 70 | %% common error in anon functions 71 | 72 | clear 73 | 74 | % different input and function variables 75 | x2fun = @(x) y.^2; 76 | 77 | x2fun(0) 78 | 79 | % now define the variable in the workspace 80 | y = 3; 81 | x2fun(0) % MATLAB version dependent: will either "work" or error 82 | 83 | %% anonymous functions in minimization problem 84 | 85 | % goal: find x that minimizes the function x^3 + x^4 86 | x3_p_x4 = @(t) (t.^3 + t.^4); % which sets of parentheses are optional? 87 | 88 | % first plot 89 | figure(1), clf 90 | x = linspace(-3,3,50); 91 | plot(x,x3_p_x4(x)); 92 | set(gca,'ylim',[-2 2]) 93 | 94 | % minimize close to some point 95 | [minvalX,minvalY] = fminsearch(x3_p_x4,0); 96 | 97 | hold on 98 | plot(minvalX,minvalY,'ro','markerfacecolor','r') 99 | 100 | %% end. 101 | -------------------------------------------------------------------------------- /scripts2/plotrandom.m: -------------------------------------------------------------------------------- 1 | function outvec = plotrandom(varargin) 2 | % PLOTRANDOM generate and plot sorted random numbers 3 | % 4 | % outvec = plotrandom(N,plottoggle) 5 | % 6 | % INPUTS: N - number of numbers to generate. 7 | % - Must be in range [5,100] 8 | % - Default value is 30 9 | % plottoggle - 0 for no plot (default), anything else for a plot 10 | % 11 | % OUTPUT: outvec - sorted random number vector 12 | % 13 | % mikexcohen.com 14 | 15 | 16 | % a function that takes 0, 1, or 2 inputs: 17 | % 1) N numbers to generate and sort (default 30). N between 5 and 100 18 | % 2) plot toggle (default false). 19 | % and outputs the sorted random numbers 20 | 21 | 22 | %% input checks 23 | 24 | % set default values if none inputted 25 | if nargin==0 26 | N = 30; 27 | plottoggle = false; 28 | elseif nargin==1 29 | N = varargin{1}; 30 | plottoggle = false; 31 | elseif nargin>1 32 | N = varargin{1}; 33 | plottoggle = varargin{2}; 34 | end 35 | 36 | % N is numeric and a single number (scalar) 37 | if ~isnumeric(N) || length(N)>1 38 | help plotrandom 39 | error('First input needs to be one number.') 40 | end 41 | 42 | % N must be between 5 and 100 43 | if N<5 || N>100 44 | help plotrandom 45 | error('First input needs to be between 5 and 100.') 46 | end 47 | 48 | 49 | %% generate random numbers and sort 50 | 51 | vec = randn(N,1); 52 | outvec = sort( vec ); 53 | 54 | %% generate a plot if requested 55 | 56 | if plottoggle 57 | 58 | % new figure 59 | figure(100), clf 60 | 61 | % plot the data 62 | plot(outvec,'ks-','linewidth',2,'markersize',16,'markerfacecolor','w') 63 | xlabel('X axis') 64 | ylabel('Y axis') 65 | title('The plot.') 66 | set(gca,'xlim',[.5 N+.5]) 67 | end 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /scripts2/uniquefx.m: -------------------------------------------------------------------------------- 1 | function ufvals = uniquefx(x,varargin) 2 | % UNIQUEFX(x[,sortF]) returns a table with unique elements and their counts 3 | % 4 | % INPUT: 5 | % x - numeric vector or matrix (matrices are vectorized) 6 | % sortF - (boolean) optional sort by frequency (default=false) 7 | % 8 | % OUTPUT: 9 | % ufvals - Nx2 matrix with unique values and their frequencies 10 | % 11 | % EXAMPLE: 12 | % >> uniquefx([1 1 3 3 3 3 7 7 7],true) 13 | % >> ans = 14 | % 1 2 15 | % 7 3 16 | % 3 4 17 | % 18 | 19 | 20 | %% input checks 21 | 22 | % make sure input is numeric 23 | if ~isnumeric(x) 24 | help uniquefx 25 | error('Input must contain all numbers!') 26 | end 27 | 28 | % if input is a matrix 29 | if ~isvector(x) 30 | x = x(:); 31 | warning('Vectorizing the matrix input.') 32 | end 33 | 34 | % determine whether to sort by frequency 35 | if nargin==1 36 | sortByFreq = false; 37 | else 38 | sortByFreq = varargin{1}; 39 | end 40 | 41 | %% main function 42 | 43 | % extract the unique elements 44 | u = unique(x); 45 | 46 | % find the frequencies 47 | ufvals = zeros(length(u),2); 48 | for ui=1:length(u) 49 | ufvals(ui,1) = u(ui); 50 | ufvals(ui,2) = sum(x==u(ui)); 51 | end 52 | 53 | % optional sort by frequency 54 | if sortByFreq 55 | ufvals = sortrows(ufvals,2); 56 | end 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /variables/MATLAB_variables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/variables/MATLAB_variables.pdf -------------------------------------------------------------------------------- /variables/onramp_variables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/variables/onramp_variables.pdf -------------------------------------------------------------------------------- /variables/onramp_variables_indexing.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Variables 5 | % VIDEO: Indexing 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% 11 | 12 | %% indexing vectors 13 | 14 | % accessing a single element of a vector 15 | vec(2) 16 | 17 | % uh oh... 18 | vec(.4) 19 | 20 | 21 | 22 | % accessing multiple elements with the colon operator 23 | vec(2:3) 24 | 25 | % uh oh... 26 | vec(1:.5:2) 27 | 28 | 29 | % accessing multiple elements directly 30 | vec([ 1 1 3 2 1 2 3 2 ]) 31 | 32 | %% indexing matrices 33 | 34 | amat(1,2:3) 35 | 36 | amat(1,[2 3]) 37 | 38 | % linear indexing (best avoided for now) 39 | amat(4:5) 40 | 41 | 42 | %% done. 43 | -------------------------------------------------------------------------------- /variables/onramp_variables_logicals.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Variables 5 | % VIDEO: Variables for logic 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% boolean (a.k.a. logicals, a.k.a. true/false) 12 | 13 | % sometimes, it's useful to know if a statement is TRUE or FALSE. 14 | % You can use a double-equals sign to ask the question of truth: 15 | 5==5 16 | 17 | % The opposite of true (1) is false (0): 18 | 5==4 19 | 20 | % not allowed: 21 | 4=5 22 | 23 | % You can assign these answers to variables: 24 | fourIsFive = 4==5; 25 | 26 | whos fourIsFive 27 | 28 | 29 | % you can use the tilde "~" to negate a statement: 30 | ~(1==1) % false because the negation of 1==1 is false 31 | ~(4>3) % also false because the negation of 4>3 is false 32 | ~(4<3) % true because it is false (~) that 4 is greater than 3. Tricky! 33 | 34 | % Remember: 35 | % One equals sign is a statement ("you have this value"). 36 | % Two equals signs means you are asking a question ("are these the same?"). 37 | 38 | 39 | %% done. 40 | -------------------------------------------------------------------------------- /variables/onramp_variables_naming.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Variables 5 | % VIDEO: Variable naming rules and recommendations 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% variable naming rules and guidelines 12 | 13 | % allowed: 14 | varb = 1; 15 | Varb = 2; 16 | vArb = 3; 17 | v_arb = 4; 18 | 19 | % not allowed: 20 | 1varb = 1; 21 | v^arb = 3; 22 | 23 | % allowed but should be avoided: 24 | a_variable_name_that_is_long_and_detailed_but_annoying_to_use = 10; 25 | a = 10; 26 | 27 | % allowed but must be avoided: 28 | linspace = 4; 29 | 30 | % case sensitive 31 | clear 32 | varb = 4; 33 | varb 34 | Varb 35 | 36 | 37 | %% done. 38 | -------------------------------------------------------------------------------- /variables/onramp_variables_numbers.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Variables 5 | % VIDEO: Variables for numbers 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% 11 | 12 | %% creating vectors using square brackets [] 13 | 14 | % 3-element row vector 15 | vec = [1 4 3]; 16 | 17 | % make it a column vector 18 | % via transpose 19 | vec = [1 4 3]'; 20 | % or via semicolons 21 | vec = [1; 4; 3]; 22 | 23 | %% creating vectors using the colon operator 24 | 25 | skipvec = 1:2:9; 26 | 27 | %% matrices 28 | 29 | amat = [ 1 2 3; 9 8 7; 3 5 2] 30 | 31 | % uh oh... 32 | amat = [ 1 2 3; 9 8 7; 3 2] 33 | 34 | 35 | %% done. 36 | -------------------------------------------------------------------------------- /variables/onramp_variables_strings.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Variables 5 | % VIDEO: Variables for strings 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% characters 11 | 12 | name = 'mike'; 13 | name = mike; 14 | 15 | char4 = '4'; 16 | 17 | %% strings 18 | 19 | nameS = "mike"; 20 | 21 | % notice: 22 | name(2) 23 | nameS(2) 24 | 25 | %% cells 26 | 27 | names = { 'mike' }; 28 | 29 | names = { name ; 4 }; % what happens without the semicolon in the middle? 30 | 31 | %% cell arrays 32 | 33 | celery{1} = [ 1 2 3 4 5 6 7 ]; 34 | celery{2} = 'hello world'; 35 | celery{3} = [ 1 3 6 7 4 3 5 6 7 87 76 43 4 5 6 767 ]; 36 | 37 | celery 38 | celery{2} 39 | 40 | %% [] {} 41 | 42 | % square brackets for concatenation 43 | [ 3 4:6 pi ] 44 | [ 'Hello ' 'my name is Mike and I like ' num2str(7) ' apples.' ] 45 | 46 | % curly brackets for cell arrays 47 | cell1 = { 4 4 5 }; 48 | cell2 = { 'hello my' 'name' 'is' 'Mike' }; 49 | 50 | 51 | 52 | %% done. 53 | -------------------------------------------------------------------------------- /variables/onramp_variables_structures.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Variables 5 | % VIDEO: Variables for structures 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% 12 | 13 | % The most flexible type of variable is a structure. Structures contain fields that 14 | % are used for different kinds of data. For example: 15 | 16 | ANTS.name = 'mike'; % ANTS = Analyzing Neural Time Series 17 | ANTS.position = 'author'; 18 | ANTS.favorite_toothpaste_flavor = 'cinnamon'; 19 | ANTS.number_of_watches = 18; 20 | ANTS.favorite_color = [ .8 .1 .8 ]; % RGB values 21 | 22 | % You can also have an array of structures 23 | ANTS(2).name = 'Mickey Mouse'; 24 | ANTS(2).position = 'learner'; 25 | ANTS(2).favorite_toothpaste_flavor = 'bratworst'; % gross, but who am I to judge? 26 | ANTS(2).number_of_watches = 1; 27 | ANTS(2).favorite_color = [ 1 1 1 ]; 28 | 29 | % now you can get information about all fields from one specific element of 30 | % the structure: 31 | ANTS(1) 32 | 33 | % or information about one field within one member: 34 | ANTS(1).number_of_watches 35 | 36 | % or information about one field from all members: 37 | ANTS.favorite_toothpaste_flavor 38 | 39 | % note that this last result came out as two separate answers. If you want 40 | % to combine them into a single output (e.g., a cell array), use curly 41 | % brackets: 42 | {ANTS.favorite_toothpaste_flavor} 43 | 44 | 45 | %% done. 46 | -------------------------------------------------------------------------------- /variables/onramp_variables_whatAre.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Variables 5 | % VIDEO: What are variables? 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% 11 | 12 | % variables as place-holders for information 13 | x = 1 14 | a = 7 15 | x + a 16 | x*a^a 17 | 18 | % reassign a value to a variable 19 | x = 4 20 | x*a^a 21 | 22 | % with a semicolon to suppress the output 23 | b = x*a^a 24 | b = x*a^a; 25 | 26 | %% variables for strings 27 | 28 | s = 'hello'; 29 | 30 | s = 3; 31 | 32 | %% longer variable names allow for interpretability 33 | 34 | mike = 72; 35 | tom = 28; 36 | mike + tom 37 | 38 | whos 39 | 40 | %% removing variables from the workspace 41 | 42 | clear x 43 | whos 44 | 45 | x + 4 46 | 47 | x = 4; 48 | xx = 5; 49 | clear x* % clears everything that starts with x 50 | 51 | clear % permanent! 52 | 53 | %% common mistakes 54 | 55 | % case-sensitive 56 | varname = 1; 57 | Varname 58 | 59 | 60 | %% done. 61 | 62 | 63 | -------------------------------------------------------------------------------- /visualize/amsterdam.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/visualize/amsterdam.bmp -------------------------------------------------------------------------------- /visualize/colorful_pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mikexcohen/MATLAB_onramp/95d2c028ac498c3b331a88ba942e7cbc5911d68a/visualize/colorful_pic.png -------------------------------------------------------------------------------- /visualize/onramp_visualization_bars.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Data visualizations 5 | % VIDEO: Making bar plots with error bars 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% basic barplots 12 | 13 | figure(3), clf 14 | 15 | % basic bar 16 | bar(1:4,[1 -2 5 4]) 17 | 18 | % specify x and y values separately 19 | bar([1 2 5 6],9:-2:3) 20 | 21 | % matrix input can be powerful but confusion 22 | mat = [1 2 3; 2 3 4]; 23 | bar(mat') % what happens when you transpose mat? 24 | 25 | %% barplots with errorbars 26 | 27 | % specify x-values 28 | x = [1 3 4 7 8]; 29 | y = [1 9 3 4 5]; 30 | e = [1 2 4 .2 .2]; 31 | 32 | % simple errorbar function 33 | subplot(211) 34 | errorbar(x,y,e,'r.') 35 | title('errorbar alone') 36 | 37 | 38 | % often looks nicer like this: 39 | subplot(212) 40 | bar(x,y) 41 | hold on 42 | errorbar(x,y,e,'.') 43 | title('bar and errorbar') 44 | 45 | 46 | %% done. 47 | -------------------------------------------------------------------------------- /visualize/onramp_visualization_exercises.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Data visualizations 5 | % VIDEO: Exercise: Find and fix the bugs! 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% Set 1 12 | 13 | plot(randn(10,3)) 14 | xlabel time 15 | ylable('amplitude') 16 | 17 | %% Set 2 18 | 19 | plot( 3 ) 20 | set('xlim',[-1 4]) 21 | 22 | %% Set 3 23 | 24 | data = randn(10,3,2); 25 | plot(data) 26 | 27 | 28 | %% done. 29 | -------------------------------------------------------------------------------- /visualize/onramp_visualization_figuresEtc.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Data visualizations 5 | % VIDEO: Importance of visualization; figure parts 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% first, a motivating example 11 | 12 | % the goals is to produce a Gaussian (normal curve) 13 | t = -.5:.01:.5; 14 | s = .04; 15 | gaussian = exp( -t.^2 / (2*s^2) ); 16 | % seems OK, MATLAB didn't crash, and the code seems to match the function 17 | 18 | 19 | % but when plotting, it doesn't look right 20 | plot(t,gaussian) 21 | 22 | %% figures 23 | 24 | figure % opens a new figures 25 | 26 | % close a figure: 27 | close 28 | 29 | % if you know the figure number, or have a handle to it (we'll get to this 30 | % later), you can also open and close specific figures. 31 | figure(10) 32 | figure(100) 33 | figure(103) 34 | 35 | close([100 ... An elipse at the end of a line allows you to write comments and continue the code on the next line. This is convenient for long lines of code that you want to be visible on a single screen without using the horizontal scrollbar. 36 | 103]) 37 | 38 | 39 | % simple plotting 40 | plot(randn(10,4)) 41 | 42 | % close all figures 43 | close all 44 | 45 | %% subplots 46 | 47 | % so far we've been putting all the data into one plot in the center of the 48 | % figure. you can also use multiple plots: 49 | figure(1) 50 | 51 | subplot(1,2,1) % 1 row, 2 columns, make the first subplot active 52 | plot(randn(10,2)) 53 | 54 | subplot(1,2,2) % 1 row, 2 columns, make the second subplot active 55 | % if <10 subplots, you can enter a single number: 56 | subplot(122) 57 | plot(randn(10,2)) 58 | 59 | 60 | %% mixed subplot geometry 61 | 62 | close all 63 | figure 64 | 65 | subplot(121) 66 | plot(randn(10,3)) 67 | 68 | % OK 69 | subplot(224) 70 | plot(randn(5)) 71 | 72 | % but... 73 | subplot(313) 74 | plot(randn(6)) 75 | 76 | %% subplots embedded inside a loop 77 | 78 | figure(1) 79 | clf % clf = clear figure 80 | 81 | for subploti=1:4 82 | subplot(2,2,subploti) 83 | plot( (-10:10).^subploti ) 84 | end 85 | 86 | %% done. 87 | -------------------------------------------------------------------------------- /visualize/onramp_visualization_getset.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Data visualizations 5 | % VIDEO: Improve your figure with get and set 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% slightly more advanced: get and set 12 | % "set" allows you to access specific properties of graphics. 13 | % set uses "parameter-value pair" operations, which you will use 14 | % often in plotting, as well as in some other advanced functions. 15 | plot(1:10,rand(10,3)) 16 | set(gca,'xtick',1:2:9); % gca = "get current axis"; note the parameter-value pair afterwards 17 | set(gca,'xtick',1:2:9,'xticklabel',{'one';'three';'five';'seven';'nine'}) % can put multiple parameter-value pairs in one function 18 | 19 | % the complement to set is get. type "get(gca)" to see a list of parameters 20 | % you can change 21 | get(gca) 22 | % you can also access (and return output from) axis properties: 23 | axis_ylim = get(gca,'YLim'); % axis_ylim is the lower and upper bounds of the y-axis 24 | 25 | 26 | % note that 'gca' points to the "current" axis, or the one most recently used. 27 | % You can mouse-click on an axis to make it current. 28 | subplot(221) 29 | plot(rand(10,3)) 30 | 31 | subplot(224) 32 | plot(rand(10,3)) 33 | set(gca,'xlim',[-4 15]) 34 | 35 | %% change figure properties 36 | 37 | % you can also change properties of figures, e.g.: 38 | set(gcf,'Color',[.6 0 .8],'name','My purple figure!','numberTitle','off') 39 | 40 | %% set: not just for axes and figures 41 | 42 | % Things can get slightly confusing, so make sure you use informative variable names. 43 | title('Hello there') 44 | titleh = get(gca,'Title'); % the "title" property is a handle to the title object 45 | %titleh = title('Hello there'); % does the same thing as the previous line 46 | get(titleh) 47 | set(titleh,'FontSize',40) 48 | set(titleh,'String','LARGE TITLE') 49 | 50 | % Let's touch up the figure with some lines showing the 0 crossings. 51 | % We can do this without needing to know the exact axis limits: 52 | figure(3), clf 53 | plot(5*randn(10,2)) 54 | hold on 55 | plot(get(gca,'xlim'),[0 0],'k') 56 | 57 | % handle to line 58 | lineh = plot([6 6],get(gca,'ylim')); 59 | get(lineh) % note: variables for handles end in h 60 | set(lineh,'linestyle','--','linewidth',2,'color','k') 61 | 62 | %% done. 63 | -------------------------------------------------------------------------------- /visualize/onramp_visualization_imagescContour.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Data visualizations 5 | % VIDEO: imagesc, contourf, and surf 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | 11 | %% basic image plotting 12 | 13 | % You can also plot images in 2D. This is useful for 2D data such as 14 | % time-frequency maps, connectivity matrices, etc. 15 | 16 | figure 17 | imagesc(randn(100)) 18 | 19 | % imagesc can also take x,y,z inputs, to make x- and y-axis values: 20 | imagesc(1:10:100,0:.1:1,randn(100)) 21 | 22 | % now let's make this a bit smoother by convoling it with a 2D gaussian 23 | xyrange = -1:.1:1; 24 | [X,Y] = meshgrid(xyrange); % this creates a grid of X and Y values 25 | gaus2d = exp(-(X.^2 + Y.^2)); 26 | 27 | % let's look at the Gaussian 28 | imagesc(gaus2d) 29 | 30 | imagesc(xyrange,xyrange,conv2(gaus2d,randn(100),'same')); 31 | 32 | % you can toggle the colorbar, which shows you the mapping between color 33 | % and value 34 | colorbar 35 | 36 | % you can also change the colormap (type "help graph3d" to see a list of 37 | % default colormaps; you can also create your own) 38 | colormap bone 39 | colormap spring 40 | colormap hot 41 | colormap jet % this is the most commonly used colormap in scientific communications 42 | % hint for how to create your own: type "cmap=jet;" columns are RGB values 43 | 44 | %% image vs contourf vs surf 45 | 46 | % there are other functions you can use for 2D data, including: 47 | figure 48 | data = conv2(gaus2d,randn(100),'same'); % 2D convolution 49 | 50 | subplot(221) % that if you don't use variables and have fewer than 10 subplots, commas are not necessary 51 | imagesc(xyrange,xyrange,data) 52 | title('function: imagesc') 53 | 54 | subplot(222) 55 | surf(xyrange,xyrange,data) 56 | shading interp 57 | title('function: surf') 58 | 59 | subplot(223) 60 | contour(xyrange,xyrange,data) 61 | title('function: contour') 62 | 63 | subplot(224) 64 | contourf(xyrange,xyrange,data,40,'linecolor','none') 65 | title('function: contourf (with more parameters)') 66 | 67 | % note how imagesc flips the y-axis! (this can be changed: " set(gca,'YDir','normal') ") 68 | 69 | % now let's change the color scaling 70 | set(gca,'clim',[-1 1]) 71 | set(gca,'clim',[-10 2]) 72 | set(gca,'clim',[-10 20]) 73 | 74 | 75 | % There are many more ways to plot data and manipulate plots; 76 | % this should get you started with the basics. 77 | 78 | % to save the figure, go File -> Save As... 79 | % you can save as .fig (readable in matlab only), pixelated formats like 80 | % .bmp or .png, or vector format like .eps (useful for importing into 81 | % Illustrator or Correl Draw) 82 | % or from the command: 83 | print('colorful_pic.png','-dpng') % creates png 84 | 85 | %% a bit more about images 86 | 87 | % Images are just matrices of numbers. So are pictures. Load in the picture 88 | % of amsterdam (note: Matlab must be in the directory in which the file lives). 89 | amsterdam = imread('amsterdam.bmp'); 90 | whos amsterdam 91 | 92 | % note that this picture is a 2 (rows) x 2 (columns) x 3 (RGB) matrix 93 | figure 94 | imagesc(amsterdam) 95 | axis image 96 | axis off % or axis on 97 | grid on % only if axis is on 98 | grid minor 99 | 100 | % try plotting the individual values separately: 101 | title_color_components='RGB'; 102 | 103 | for subploti=1:4 104 | 105 | subplot(2,2,subploti) 106 | 107 | if subploti<4 108 | imagesc(amsterdam(:,:,subploti)) 109 | title([ 'Plotting just the ' title_color_components(subploti) ' dimension.' ]) 110 | colormap gray 111 | else 112 | imagesc(amsterdam) 113 | title('Plotting all colors') 114 | end 115 | 116 | % affects all subplots 117 | axis off, axis square 118 | end 119 | 120 | 121 | %% done. 122 | -------------------------------------------------------------------------------- /visualize/onramp_visualization_plotting.m: -------------------------------------------------------------------------------- 1 | %% 2 | % COURSE: MATLAB onramp: coding, concepts, confidence, style 3 | % 4 | % SECTION: Data visualizations 5 | % VIDEO: Plotting lines in 2D and 3D 6 | % 7 | % TEACHER: Mike X Cohen, sincxpress.com 8 | % 9 | 10 | %% basic 2D plotting 11 | 12 | figure(1), clf 13 | plot(1:10,(1:10).^2); % plot X by Y 14 | 15 | % run this line after the previous one. note that it overwrites the 16 | % previous plot 17 | plot(1:10,log(1:10)) 18 | 19 | % alleviated with the hold command 20 | hold on 21 | plot(1:10,(1:10).^1.5); % plot X by Y 22 | hold off 23 | plot(randn(4)) 24 | 25 | 26 | % basic plotting color customization 27 | clf 28 | plot(1:10,(1:10).^2,'linewidth',3); 29 | hold on 30 | plot(1:10,log(1:10)*30,'r-d') % plot in red and with thicker lines. type "help plot" to learn more 31 | 32 | %% draw a straight line 33 | 34 | % Drawing a line is simple, but can be a bit tricky at first. You need to 35 | % define the start and end points in the X and Y (and also Z if you are 36 | % plotting in 3D) axes: 37 | plot([2 9],[60 60],'k') 38 | plot([1 10],[0 100],'m:') 39 | 40 | % now release the hold 41 | hold off 42 | 43 | % Of course, you can plot the information in variables: 44 | subplot(211) 45 | x = 0:.1:1; 46 | y = exp(x); 47 | plot(x,y,'.-') 48 | 49 | % x and y need to be of equal length, otherwise you'll get an error: 50 | x = 0:.1:1; 51 | y = [0 exp(x)]; 52 | plot(x,y,'.-') 53 | 54 | % you can plot multiple lines simultaneously if they are in a matrix 55 | cla % clear axis; note the difference between cla and clf 56 | plot(100:100:1000,rand(10,3)) 57 | 58 | % now let's add some extra features... 59 | title('Random lines') 60 | xlabel('x-axis label... maybe time? maybe space?') 61 | ylabel('voltage (\muV)') % note that the "\mu" is converted to the greek lower-case character 62 | legend({'line 1';'line 2';'line 3'}) % this is a cell array! 63 | 64 | %% plotting lines in 3D 65 | 66 | % If you feel constrained by two dimensions, fear not! Matlab also allows you to 67 | % plot data in three dimensions. This becomes particularly handy for complex functions 68 | % such as Fourier transform and wavelet convolution. 69 | 70 | % Plotting a line in a 3D space is easy. First, define data in 3 dimensions. 71 | n = 10; 72 | dataX = rand(1,n); 73 | dataY = randn(1,n); 74 | dataZ = rand(1,n)*10; 75 | 76 | % Now simply use plot3 the same way you would use plot, 77 | % but with three inputs: 78 | figure(2), clf 79 | plot3(dataX,dataY,dataZ) 80 | 81 | grid on % sometimes useful 82 | 83 | rotate3d on % this command will allow you to click-and-drag on the figure to spin the data around 84 | 85 | % adding other features to the plot works the same as with a normal plot, 86 | % e.g., 87 | xlabel('X-axis') 88 | ylabel('Y-axis') 89 | zlabel('Z-axis') 90 | 91 | 92 | % You might instead have a 3D matrix, e.g., 93 | data3d = randn(3,30); 94 | plot3(data3d) 95 | % Although the previous line seems like it should work, it unfortunately 96 | % doesn't. You'll need to input each dimension separately: 97 | plot3(data3d(1,:),data3d(2,:),data3d(3,:),'ko-','linew',3,'markerface','m','markersize',10) % you can use the same extra inputs to define line features as you would with the normal plot function 98 | axis off 99 | axis square % also try tight and normal 100 | 101 | 102 | %% done. 103 | --------------------------------------------------------------------------------