Mithat Konar
2019-04-26
a = 3.14159 b = a + 5 c = sin(a); foo = 'How''s it?'
% a single line comment a = 99; % this works too %{ foo = 'multiple line comments'; baz = 'use curly brackets inside'; qux = 'a pair of percent signs.'; %}
a = [5 4 2 1] b = 1 : 10 % [1, 2, ... , 10] t = 0 : 0.1 : 1 % 0 to 1 in 0.1 steps x = 0 : 0.1 : 2*pi % 0 to 2π in 0.1 steps
x = 0.3 + 0.4i;
% separate matrix rows with ';' a = [1 2 3; 4 5 6; 7 8 9]; b = [9 8 7; 6 5 4; 3 2 1];
r = 1.25 * a; % scalar multiplication r = a * b; % matrix multiplication r = a .* b; % elementwise multiplication r = a ./ b; % elementwise division
r = inv(a); % inverse r = a'; % transpose
% individual element (row, col) a(3, 2); % submatrix (row range, col range) bigMatrix(1:3, 10:end); % set values of submatrix, all cols bigMatrix(1:3, :) = -1;
% display info about variables in current workspace: whos
help what-you-want-help-with
sqrt(x)
: square rootmod(a, b)
: modulus after divisionones(m, n)
, zeros(m, n)
: matrix of all ones or zerosrand(m, n)
: matrix of random numberslinspace(x1, x2, n)
: n linear points between x1 and x2switch switch_expr case case_expr, statement, ..., statement case {case_expr1, case_expr2, case_expr3,...} statement, ..., statement ... otherwise, statement, ..., statement end
switch_expr
doesn't need to be a numbercase
can match multiple valueswhile n < 10 y = y * n; n = n + 1; end
On one line:
while n < 10, y = y * n; n = n + 1; end
a < b
, lt(a, b)
a > b
, gt(a, b)
a <= b
, le(a, b)
a >= b
, ge(a, b)
a == b
, eq(a, b)
a ~= b
, ne(a, b)
a && b
: short-circuit logical AND (scalars only)a || b
: short-circuit logical OR (scalars only)a & b
, and(a, b)
: element-wise logical AND (scalars or vectors)a | b
, or(a, b)
: element-wise logical OR (scalars or vectors)~a
, not(a)
: logical NOTxor(a, b)
: logical EXCLUSIVE ORany(a)
: true if any element of vector is nonzeroall(a)
: true if all elements of vector are nonzero .m
file with a main
function..m
.m
file or interactively.function area = traparea(a, b, h) area = 0.5 * (a + b) * h; end
% Uses traparea function defined in traparea.m area1 = traparea(1, 2, 3); disp(area1);
help function-name
.function area = traparea(a, b, h) % traparea(a, b, h) Computes the area of a trapezoid given % the dimensions a, b and h, where a and b % are the lengths of the parallel sides and % h is the distance between these sides. area = 0.5 * (a + b) * h; end
userpath
: list the directories where MATLAB looks for m-files.addpath
: add additional directories where MATLAB looks for m-files.savepath
: make changes permanent.pathtool
: launch a GUI to manage paths.