```matlab % QCB W12: Intro to MatLab Fall 2024 % Day 1 % --------------------------------- % comments ``` # Section breaks ```matlab a=1; display(a) ``` ```matlab b=2; display(b) ``` ```matlab display(a+b) ``` # Variables ```matlab % assignment command: put a value on the right side of '=' into % a 'pigeon hole' named on the left %a = 2 %b = 4; %c = a + b; % this is *not* an equation !!! ``` # Values & math functions ```matlab %a = 1; % note: numbers are, in general, complex - i = sqrt(-1) %b = 1e-3; % scientific notation % common math operations/functions %c = 1 + 2*3 + 2 * 3^2; % Note: some other languages use ** in place of ^ %d = sin(0) + cos(pi); % trig functions %e = exp(-10/100); % same as exp(1)^(-10/100) %f = log(1) +log2(2) + log10(10); % different bases %g = sqrt(-2); % Note: this is valid - complex numbers are OK !!! %s = 'this is a string'; ``` # Every variable (and every value) can be a matrix (aka array) ```matlab % create by hand %--------------- %A = [1,2,3,4,5,6]; % 1 row, 5 columns; check with size(A) %B = [1;2;3;4;5;6]; % 5 rows, 1 column %C = [1,2,3;4,5,6]; % 2 rows, 3 columns (commas are optional) %A10 = 10 * A % concatanation %-------------- %D = cat( 1, A, A ); % example of a function: like math % - takes argument(s) % - may return value(s) %E = circshift(A,1); % another function... % access element(s) %----------------- % A(1) + B(5,1) + C(2,3) % note: idices start with 1 (NOT zero !!!) % A(2:4) % 'slice' ; note: 4th element *is* included % A(3:end) % A(3:end-2) % matrix 'discovery' functions %----------------------------- numel(A) % number of elements size(A) % dimensions length(A) % largest dimension % matrix construction tools %-------------------------- % useful functions %----------------- %Z = zeros(4,6); %O = ones(6,4); %I = eye(4); % note: square matrix !!! % ranges %------- %R10 = 1:10; % Note: 10 elements (defult step - 1) %R20 = 1:0.5:10; % Explicit step (0.5) % random numbers %--------------- % reshuffled range (random parmutationrange) %Ar = randomperm(10) % uniform distribution over (0,1) range %U42 = rand(4,2); % 4 x 2 array of random numbers %U44 = rand(4); % same as above but square matrix %normal distribution %N42 = randn(4,2) % 4 x 2 array of rande %N44 = randn(4) % same as above, square matrix ``` # saving/loading workspace ```matlab %save myworkspace.mat %load myworkspace.mat ``` # for loops ```matlab %for ii = 1:10 % fprintf("%5i %6i %.3f %.3f\n", ii, ii^2, sqrt(ii), ii^2+3*randn(1) ); %end ``` # saving data ```matlab myOutFile = "mydata_1.tab"; % %fout = fopen(myOutFile, 'w'); %for ii = 1:10 % fprintf(fout, "%5i %6i %.3f %.3f %.3f\n", ii, ii^2, ii+2*randn(1), ii^2+3*randn(1) ); %end %fclose(fout); ``` # reading data mydata=importdata(myOutFile); ```matlab % mydata=importtable(myOutFile); ```