MATLAB Notes
1. Data and Data Flow in MATLAB
• MATLAB is a matrix-based programming environment.
• Data types include numeric, character, logical, cell, structure, etc.
• Workspace: Stores variables created during execution.
• Data Flow:
o Data input → Processing using operators/functions → Output
(display, plot, file).
o Example:
o x = [1 2 3 4]; % Input
o y = x.^2; % Processing
o disp(y); % Output
2. Vectors
• A vector is a 1D array (row or column).
• row = [1 2 3 4]; % Row vector
• col = [1; 2; 3; 4]; % Column vector
• Indexing:
• row(2) % 2nd element → 2
• col(3) % 3rd element → 3
3. Matrix Operations & Operators
• Matrix creation:
• A = [1 2; 3 4];
• B = [5 6; 7 8];
• Operators:
o Addition/Subtraction: A + B, A - B
o Multiplication: A * B (matrix multiplication), A .* B (element-wise)
o Division: A / B, A ./ B
o Power: A^2, A.^2 (element-wise)
• Transpose: A'
4. Reshaping Matrices
• Change dimensions using reshape:
• A = [1 2 3 4 5 6];
• B = reshape(A, 2, 3); % 2 rows, 3 columns
5. Arrays
• MATLAB supports multi-dimensional arrays.
• A = rand(3,3,2); % 3×3×2 array
• Access elements:
• A(2,3,1) % element at row=2, col=3, page=1
6. Colon Notation
• Range creation:
• v = 1:5; % [1 2 3 4 5]
• v = 0:2:10; % [0 2 4 6 8 10]
• Submatrix extraction:
• A = [1 2 3; 4 5 6; 7 8 9];
• A(:,2) % all rows, 2nd column → [2;5;8]
• A(1,:) % 1st row → [1 2 3]
7. Numbers
• Numeric types: double (default), single, int8, int16, int32, etc.
• Example:
• x = int16(100);
• class(x) % returns 'int16'
8. Strings
• Two types:
o Character arrays: 'Hello'
o String objects: "Hello"
• Concatenation:
• s1 = "Data";
• s2 = "Flow";
• s = s1 + " " + s2; % "Data Flow"
• Functions: strlength, strcat, split, upper, lower.
9. Functions
• User-defined functions:
• function y = squareNum(x)
• y = x^2;
• end
• Stored in a separate .m file with the same name.
• Anonymous functions:
• f = @(x) x^2 + 2*x + 1;
• f(3) % 16
10. File Input-Output
• Reading/Writing text files:
• % Write
• fid = fopen('[Link]','w');
• fprintf(fid,'Hello MATLAB\n');
• fclose(fid);
•
• % Read
• fid = fopen('[Link]','r');
• line = fgetl(fid);
• fclose(fid);
• MAT-files (native format):
• save [Link] A B % save variables
• load [Link] % load variables
11. Importing and Exporting Data
• CSV:
• T = readtable('[Link]'); % import
• writetable(T,'[Link]'); % export
• Excel:
• xlsread('[Link]');
• xlswrite('[Link]',A);
• Other formats: MATLAB supports .mat, .txt, .dat, .json, SQL databases,
etc.