x = randi(10, 1, 10)
[x_sorted, idx_order] = sort(x)
x(idx_order)
[x_sorted_descend, ~] = sort(x, 'descend')
profile on
M = magic(100);
profile off
info = profile('info')
profile clear
info.FunctionTable.FunctionName
% convert total time to an array with square brackets
TotalTime = [info.FunctionTable.TotalTime]
% sort in the descending order, most total time first
[TT_sorted, idx] = sort(TotalTime, 'descend');
idx
% convert FunctionNames to a cell array with curly braces
Names = {info.FunctionTable.FunctionName};
Names = Names(idx) % reorder a cell array with parentheses, access elements with curly braces
function x = solveAb(A, b)
% solves the system of equations (matrix equation)
% A x = b
% where A, b are known and x is unknown
Ainv = pinv(A);
x = Ainv * b;
end
N = 1e3;
A = rand(N, N);
b = rand(N, 1);
profile on
x = solveAb(A, b);
profile off
info = profile('info');
profile clear
% check how well we do, should give close to 0 if A x = b
sum(abs(A * x - b))
tt = [info.FunctionTable.TotalTime];
[tt_sorted, idx] = sort(tt, 'descend');
tt_sorted
Names = {info.FunctionTable.FunctionName};
Names(idx)
Errors break execution, so use them when program should not continue.
error('This is an erorr');
function change_third_element(a)
if length(a) < 3
error('Argument is not long enough');
end
a(3) = -1;
end
change_third_element([1, 2, 3])
change_third_element([1, 2])
A = rand(4, 4);
x = rand(3, 1);
% in-built functions also produce errors
A * x
Errors are used more often.
function x = add2_to_third_el(x)
if length(x) < 3
warning('Argument is not long enough, returning unchanged');
else
x(3) = x(3) + 2;
end
end
add2_to_third_el([1, 2, 3])
add2_to_third_el([1, 2])
A = [rand(3, 3), zeros(3, 1); zeros(1, 4)]
inv(A)
Disabling warnings.
warning('off');
A = [rand(3, 3), zeros(3, 1); zeros(1, 4)];
inv(A)
warning('on');
A = [rand(3, 3), zeros(3, 1); zeros(1, 4)];
inv(A)