Contents

% Ponieważ nie można użyć funkcji publish dla skryptów zawierających
% polecenie input skrytp został zmodyfikowany, tak aby uniknąc problemów
% wynikajacych z tego ograniczenia.
% W celu przetsestowania przykładów zawierających polecenie input należy
% odkomentować właściwy fragment kodu.

Funkcje uzytkownika - definicja wywołanie

type calcarea
	function area = calcarea(rad)
	% This function calculates the area of a circle
	area = pi * rad * rad;
    
    end
help calcarea
  This function calculates the area of a circle

pole = calcarea(4)
pole =
   50.2655
type script1c
% script1c % wywołanie skrypu zakomentowane z powodu funkcji input
% Ten program wyznacza powierzchnię koła
% Program prosi użytkownika o podanie wartoci promienia koła
 
% Zachęta dla użytkownika do podania wartości promienia i pobranie wartości
% promienia
promien = input('Podaj wartość promienia: ');
% Wyznaczenie powierzchni koła
pole = calcarea(promien);
% Wyświetlenie wyniku w postaci pełnego zdania
fprintf('Pole powierzchni koła o promieniu %.2f wynosi %.2f\n', promien, pole)

Funkcje - przekazywanie większej liczby argumentów

type conevol
function outarg = conevol(radius, height)
% Calculates the volume of a cone

outarg = (pi/3) * radius * radius * height;
conevol(5,15)
ans =
  392.6991
type cylcost
function [outcost cost] = cylcost(radius, height, cost)
% Calculates the cost of constructing a closed cylinder

% The radius and height are in meters
% The cost is in US $ per square foot

% Calculate surface area in square inches
surf_area = 2 * pi * radius * height + 2 * pi * radius ^ 2;

% Convert surface area in square feet and round up
surf_areasf = ceil(surf_area/0.0929);

% Calculate cost
outcost = surf_areasf * cost;
cylcost(1.3,3,10)
ans =
        3790

Operatory relacji

help ops
  Operators and special characters.
 
  Arithmetic operators.
    plus       - Plus                               +    
    uplus      - Unary plus                         +    
    minus      - Minus                              -    
    uminus     - Unary minus                        -    
    mtimes     - Matrix multiply                    *    
    times      - Array multiply                    .*    
    mpower     - Matrix power                       ^    
    power      - Array power                       .^    
    mldivide   - Backslash or left matrix divide    \    
    mrdivide   - Slash or right matrix divide       /    
    ldivide    - Left array divide                 .\    
    rdivide    - Right array divide                ./    
    idivide    - Integer division with rounding option.
    kron       - Kronecker tensor product   
 
  Relational operators.
    eq         - Equal                             ==     
    ne         - Not equal                         ~=     
    lt         - Less than                          <      
    gt         - Greater than                       >      
    le         - Less than or equal                <=     
    ge         - Greater than or equal             >=     
 
  Logical operators.
    relop      - Short-circuit logical AND         &&     
    relop      - Short-circuit logical OR          ||     
    and        - Element-wise logical AND           &      
    or         - Element-wise logical OR            |      
    not        - Logical NOT                        ~      
    punct      - Ignore function argument or output ~
    xor        - Logical EXCLUSIVE OR
    any        - True if any element of vector is nonzero
    all        - True if all elements of vector are nonzero
 
  Special characters. 
    colon      - Colon                              : 
    paren      - Parentheses and subscripting      ( )              
    paren      - Brackets                          [ ]     
    paren      - Braces and subscripting           { }          
    punct      - Function handle creation           @
    punct      - Decimal point                      .      
    punct      - Structure field access             .      
    punct      - Parent directory                   ..     
    punct      - Continuation                       ...    
    punct      - Separator                          ,      
    punct      - Semicolon                          ;      
    punct      - Comment                            %      
    punct      - Invoke operating system command    !            
    punct      - Assignment                         =
    punct      - Quote                              '      
    transpose  - Transpose                         .'
    ctranspose - Complex conjugate transpose        ' 
    horzcat    - Horizontal concatenation          [,]     
    vertcat    - Vertical concatenation            [;]     
    subsasgn   - Subscripted assignment          ( ),{ },.   
    subsref    - Subscripted reference           ( ),{ },.   
    numArgumentsFromSubscript - Number of arguments for indexing methods
    subsindex  - Subscript index
    metaclass  - Metaclass for MATLAB class         ?
 
  Bitwise operators.
    bitand     - Bit-wise AND.
    bitcmp     - Complement bits.
    bitor      - Bit-wise OR.
    bitxor     - Bit-wise XOR.
    bitset     - Set bit.
    bitget     - Get bit.
    bitshift   - Bit-wise shift.
 
  Set operators.
    union      - Set union.
    unique     - Set unique.
    intersect  - Set intersection.
    setdiff    - Set difference.
    setxor     - Set exclusive-or.
    ismember   - True for set member.
 
  See also ARITH, RELOP, SLASH, FUNCTION_HANDLE.

logwyr = 3 < 5
logwyr =
     1
logwyr = 9 < 2
logwyr =
     0
logwwyrPlus = logwyr + 3
logwwyrPlus =
     3
logChar = 'a' < 'c'
logChar =
     1

Operatory logiczne

help ops
  Operators and special characters.
 
  Arithmetic operators.
    plus       - Plus                               +    
    uplus      - Unary plus                         +    
    minus      - Minus                              -    
    uminus     - Unary minus                        -    
    mtimes     - Matrix multiply                    *    
    times      - Array multiply                    .*    
    mpower     - Matrix power                       ^    
    power      - Array power                       .^    
    mldivide   - Backslash or left matrix divide    \    
    mrdivide   - Slash or right matrix divide       /    
    ldivide    - Left array divide                 .\    
    rdivide    - Right array divide                ./    
    idivide    - Integer division with rounding option.
    kron       - Kronecker tensor product   
 
  Relational operators.
    eq         - Equal                             ==     
    ne         - Not equal                         ~=     
    lt         - Less than                          <      
    gt         - Greater than                       >      
    le         - Less than or equal                <=     
    ge         - Greater than or equal             >=     
 
  Logical operators.
    relop      - Short-circuit logical AND         &&     
    relop      - Short-circuit logical OR          ||     
    and        - Element-wise logical AND           &      
    or         - Element-wise logical OR            |      
    not        - Logical NOT                        ~      
    punct      - Ignore function argument or output ~
    xor        - Logical EXCLUSIVE OR
    any        - True if any element of vector is nonzero
    all        - True if all elements of vector are nonzero
 
  Special characters. 
    colon      - Colon                              : 
    paren      - Parentheses and subscripting      ( )              
    paren      - Brackets                          [ ]     
    paren      - Braces and subscripting           { }          
    punct      - Function handle creation           @
    punct      - Decimal point                      .      
    punct      - Structure field access             .      
    punct      - Parent directory                   ..     
    punct      - Continuation                       ...    
    punct      - Separator                          ,      
    punct      - Semicolon                          ;      
    punct      - Comment                            %      
    punct      - Invoke operating system command    !            
    punct      - Assignment                         =
    punct      - Quote                              '      
    transpose  - Transpose                         .'
    ctranspose - Complex conjugate transpose        ' 
    horzcat    - Horizontal concatenation          [,]     
    vertcat    - Vertical concatenation            [;]     
    subsasgn   - Subscripted assignment          ( ),{ },.   
    subsref    - Subscripted reference           ( ),{ },.   
    numArgumentsFromSubscript - Number of arguments for indexing methods
    subsindex  - Subscript index
    metaclass  - Metaclass for MATLAB class         ?
 
  Bitwise operators.
    bitand     - Bit-wise AND.
    bitcmp     - Complement bits.
    bitor      - Bit-wise OR.
    bitxor     - Bit-wise XOR.
    bitset     - Set bit.
    bitget     - Get bit.
    bitshift   - Bit-wise shift.
 
  Set operators.
    union      - Set union.
    unique     - Set unique.
    intersect  - Set intersection.
    setdiff    - Set difference.
    setxor     - Set exclusive-or.
    ismember   - True for set member.
 
  See also ARITH, RELOP, SLASH, FUNCTION_HANDLE.

xor(3 < 5, 'a' > 'c')
xor(3 < 5, 'a' < 'c')
ans =
     1
ans =
     0

Instrukcja if

num = -4;
if num < 0
    num = abs(num)
end
num =
     4
num = 5;
if num < 0
    num = abs(num)
end
type sqrtifexamp
% sqrtifexamp % wywołanie skrypu zakomentowane z powodu funkcji input
% Prompt the user for a number and print its square root

num = input('Please enter a number: ');

% If the user entered a negative number, change it
if num < 0
    num = abs(num);
end
fprintf('The  sqrt of %.1f is %.1f\n',num,sqrt(num))
type sqrtifexampii
% sqrtifexampii % wywołanie skrypu zakomentowane z powodu funkcji input
% Prompt the user for a number and print its square root

num = input('Please enter a number: ');

% If the user entered a negative number, tell
% the user and change it
if num < 0
    disp('OK, we''ll use the absolute value')
    num = abs(num);
end
fprintf('The  sqrt of %.1f is %.1f\n',num,sqrt(num))

Reprezentacja prawdy i fałszu

if 5
    disp('Yes, this is true!')
end
Yes, this is true!
if -1
    disp('Yes, this is true!')
end
Yes, this is true!
if 0
    disp('Yes, this is true!')
end

letter = input('Choice (Y/N): ', 's')

letter = 'n'
letter == 'y' | 'Y' % prioryetet operatorów (precedence)
letter =
n
ans =
     1
letter == 'y' | letter == 'Y'
letter == ('y' | 'Y')
ans =
     0
ans =
     0

Instrukcja if-else

if rand <0.5
    disp('It was less then 0.5!')
else
    disp('It was not less then 0.5!')
end
It was not less then 0.5!
type checkradius
% checkradius % wywołanie skrypu zakomentowane z powodu funkcji input
% This script calculates the area of a circle
% It error-checks the user's radius
radius = input('Please enter the radius: ');
if radius <= 0
    fprintf('Sorry; %.2f is not a valid radius\n',radius)
else
    area = calcarea(radius);
    fprintf('For a circle with a radius of %.2f,',radius)
    fprintf(' the area is %.2f\n',area)
end

Zagnieżdżone instrukcje if-else

type calcy1
function y = calcy2(x)
if x < -1
    y = 1;
end
if x >= -1 & x <=2
    y = x^2;
end
if x>2
    y = 4;
end
calcy1(5)
ans =
     4
type calcy2
function y = calcy2(x)

if x < -1
    y = 1;
else
    if x <=2
        y = x^2;
    else
        y = 4;
    end
end
calcy2(5)
ans =
     4
type calcy3
function y = calcy3(x)
if x < -1
    y = 1;
elseif x <=2
    y = x^2;
else
    y = 4;
end
calcy3(5)
ans =
     4

Instrukcja switch

type letgrade
function grade = letgrade(quiz)
% This function returns the letter grade corresponding
%   to the integer quiz grade argument

% First, error-check
if quiz < 0 || quiz > 10
    grade = 'X';
    
% If here, it is valid so figure out the
%  corresponding letter grade
elseif quiz == 9 || quiz == 10
    grade = 'A';
elseif quiz == 8
    grade = 'B';
elseif quiz == 7
    grade = 'C';
elseif quiz == 6
    grade = 'D';
else
    grade = 'F';
end
letgrade(9)
ans =
A
type switchletgrade
function grade = switchletgrade(quiz)
% This function returns the letter grade corresponding
%   to the integer quiz grade argument using switch
 
% First, error-check
if quiz < 0 || quiz > 10
    grade = 'X';
else
    % If here, it is valid so figure out the
    %  corresponding letter grade using a switch
    switch quiz
        case {10,9}
            grade = 'A';
        case 8
            grade = 'B';
        case 7
            grade = 'C';
        case 6
            grade = 'D';
        otherwise
            grade = 'F';
    end
end
switchletgrade(9)
ans =
A
type switcherror
% switcherror % wywołanie skrypu zakomentowane z powodu funkcji input
% Example of otherwise for error message

choice = input('Enter a 1, 3, or 5: ');

switch choice
    case 1
        disp('It''s a one!!')
    case 3
        disp('It''s a three!!')
    case 5
        disp('It''s a five!!')
    otherwise
        disp('Follow directions next time!!')
end
mypick = menu('Pick a pizza','Cheese','Shroom','Sausage')
mypick =
     1
type pickpizza
%This script asks the user for a type of pizza
% and prints which type to order using a switch

mypick = menu('Pick a pizza','Cheese',  ...
    'Shroom','Sausage');
switch mypick
    case 1
        disp('Order a cheese pizza')
    case 2
        disp('Order a mushroom pizza')
    case 3
        disp('Order a sausage pizza')
    otherwise
        disp('No pizza for us today')
end
pickpizza
Order a mushroom pizza
type pickpizzaifelse
%This script asks the user for a type of pizza
% and prints which type to order using a nested if-else

mypick = menu('Pick a pizza','Cheese','Shroom','Sausage');
if mypick == 1
   disp('Order a cheese pizza')
elseif mypick == 2
   disp('Order a mushroom pizza')
elseif mypick == 3  
   disp('Order a sausage pizza')
else
   disp('No pizza for us today')
end
pickpizzaifelse
Order a sausage pizza

Pętla for

n=10
Suma_1 = sum_1_to_n(n)
n =
    10
Suma_1 =
    55
type myvecsum
function outarg = myvecsum(vec)
% This function sums the elements in a vector

outarg = 0;
for i = 1:length(vec)
    outarg = outarg + vec(i);
end
wektor = [9 2 6 4 7 8 1 2 3]
Suma_3 = myvecsum(wektor)
wektor =
     9     2     6     4     7     8     1     2     3
Suma_3 =
    42
sumbiez=0;
for i = wektor
    sumbiez = sumbiez + i;
    [i sumbiez]
end
Suma_3 = sumbiez
ans =
     9     9
ans =
     2    11
ans =
     6    17
ans =
     4    21
ans =
     7    28
ans =
     8    36
ans =
     1    37
ans =
     2    39
ans =
     3    42
Suma_3 =
    42
Suma_4 = sum(wektor)
Suma_4 =
    42
type myvecprod
function outarg = myvecprod(vec)
% This function finds the product of
% the elements in a vector

outarg = 1;
for i = 1:length(vec)
    outarg = outarg * vec(i);
end
iloczyn_1 = myvecprod(wektor)
iloczyn_2 = prod(wektor)
iloczyn_1 =
      145152
iloczyn_2 =
      145152
iloczyn_3 = myvecprod(1:5)
iloczyn_4 = prod(1:5)
iloczyn_3 =
   120
iloczyn_4 =
   120
silnia = factorial(5)
silnia =
   120
1:5
cumsum(1:5)
cumprod(1:5)
ans =
     1     2     3     4     5
ans =
     1     3     6    10    15
ans =
     1     2     6    24   120

Prealokacja wektora

type myveccumsum
myveccumsum(1:5)
function outvec = myveccumsum(vec)
% This function imitates cumsum for a vector

outvec = [];
runsum = 0;
for i = 1:length(vec)
    runsum = runsum + vec(i);
    outvec = [outvec runsum];
end
ans =
     1     3     6    10    15
type myveccumsumii
myveccumsumii(1:5)
function outvec = myveccumsumii(vec)
% This function imitates cumsum for a vector
% It preallocates the output vector

outvec = zeros(size(vec));
runsum = 0;
for i = 1:length(vec)
    runsum = runsum + vec(i);
    outvec(i) = runsum;
end
ans =
     1     3     6    10    15
tic; myveccumsum(1:10000); toc
tic; myveccumsumii(1:10000); toc
Elapsed time is 0.045393 seconds.
Elapsed time is 0.003911 seconds.

for i if

wektor
wektor =
     9     2     6     4     7     8     1     2     3
type myminvec
function outmin = myminvec(vec)
% Finds the minimum value in a vector

outmin = vec(1);
for i = 2:length(vec)
    if vec(i) < outmin
        outmin = vec(i);
    end
end
myminvec(wektor)
ans =
     1
min(wektor)
ans =
     1
for i = 1:10
fprintf('Będę stosował pętle for tylko tam gdzie jest to niezbędne\n');
end
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne
Będę stosował pętle for tylko tam gdzie jest to niezbędne

for i input

ww = input('wprowadz wektor: ') forecho % wywołanie skrypu zakomentowane z powodu funkcji input wektor_1 = forinputvec(5) % wywołanie funkcji zakomentowane z powodu funkcji input

zagnieżdżone pętle for

type printstars
% Prints a box of stars
% How many will be specified by 2 variables
%  for the number of rows and columns

rows = 3;
columns = 5;
% loop over the rows
for i=1:rows
    % for every row loop to print *'s and then one \n
    for j=1:columns
        fprintf('*')
    end
    fprintf('\n')
end
printstars
*****
*****
*****
type multtable
function outmat = multtable(rows, columns)
% Creates a matrix which is a multiplication table

outmat = zeros(rows,columns);
for i = 1:rows
    for j = 1:columns
        outmat(i,j) = i * j;
    end
end
multtable(10,10)
ans =
     1     2     3     4     5     6     7     8     9    10
     2     4     6     8    10    12    14    16    18    20
     3     6     9    12    15    18    21    24    27    30
     4     8    12    16    20    24    28    32    36    40
     5    10    15    20    25    30    35    40    45    50
     6    12    18    24    30    36    42    48    54    60
     7    14    21    28    35    42    49    56    63    70
     8    16    24    32    40    48    56    64    72    80
     9    18    27    36    45    54    63    72    81    90
    10    20    30    40    50    60    70    80    90   100
type createmulttab
% Prompt the user for rows and columns and
%  create a multiplication table to store in
%  a file "mymulttable.dat"

num_rows = input('Enter the number of rows: ');
num_cols = input('Enter the number of columns: ');
multmatrix = multtable(num_rows, num_cols)
save mymulttable.dat multmatrix -ascii

createmulttab % wywołanie skrypu zakomentowane z powodu funkcji input

type mymatsum
function outsum = mymatsum(mat)
% Calculates the overall sum of the elements
% in a matrix
[row col] = size(mat);
outsum = 0;

% The outer loop is over the rows
for i = 1:row
    for j = 1:col
        outsum = outsum + mat(i,j);
    end
end
mat = [3:5; 2 5 7]
mat =
     3     4     5
     2     5     7
mymatsum(mat)
ans =
    26
sum(mat)
ans =
     5     9    12
sum(sum(mat))
sum(mat(:))
ans =
    26
ans =
    26
sum(mat,1)
sum(mat,2)
ans =
     5     9    12
ans =
    12
    14

Kolejność przeglądania macierzy

mat = rand(1000);
tic, mymatsum(mat), toc
tic, mymatsumb(mat), toc
ans =
   5.0032e+05
Elapsed time is 0.065110 seconds.
ans =
   5.0032e+05
Elapsed time is 0.064124 seconds.