Just a series of Matlab commands.
a = 2;
a^20
sin(a)
a + 2 * factorial(13) / 1e9 + (2 + 2) * 2
A much better option than scripts. A function with no arguments and no outputs is a script.
They usually leave in separate files (a file per function).
The file name must match the function name!
These notebooks, however, let me defined functions right here (for convenience).
function output = my_function(input1, input2)
output = input1^2 + input2; % suppress with a semicolon (typically)
end
Function call, calling a function, with arguments gives the output value back to where the function was called from.
my_function(1, 2)
a = my_function(1, 2);
a
Use square brackets if more than one output.
Most often just right two separate functions instead of one with two (or more) outputs.
Multiple output arguments are usually only usefull when two things are computed in a common procedure together anyway.
function [output1, output2] = my_function(input1, input2, input3)
output1 = input3;
a = input1 / input2;
output2 = a;
end
Use square brackets to capture the values from the function.
[out1, out2] = my_function(1, 2, 3)
If only one variable is captured, then it is the first.
a = my_function(1, 2, 3)
You can directly ignore an output with a tilde $\verb|~|$
[~, b] = my_function(1, 2, 3)
b
~ % you can't use this as a variable, this is a special thing
An example of a multiple output in-built function when things are computed together.
v = rand(1, 10)
[max_item, index_of_max] = max(v)
v(index_of_max)
Just use $\verb|%|$ to comment.
Or a pair of $\texttt{%\{}$ and $\texttt{%\}}$ to comment out an entire block of text/code.
% a single line comment
a = 2; % a comment after code ends on the line
%{
A block comment for a longer description.
%}
%{ Or to disable some code for now.
A = zeros(4, 4);
A(1, 2) = 7 - 14 * rand();
-abs(A);
%}
a = 2.0
sin(2.0)
my_function(1, 2, 3)
disp(a);
disp(my_function(1, 2, 3));
% fprintf('<format string>', var1, var2);
fprintf('My number, a, is equal to %d\n', a);
$\texttt{%d}$ - decimal/integer
$\texttt{%i}$ - integer
$\texttt{%f}$ - floating point, a "nubmer with a comma", like 2.43543534452 or $\pi$
$\texttt{%s}$ - string
fprintf('My name is %s and I''m %i years old\n', 'Robert', factorial(17));
$\texttt{\\n}$ is the newline character, it's typed as with a backslash and $\texttt{n}$, but it really is only one character
Don't forget it.
fprintf('a = %d', 2);
fprintf('b = %f', pi);