Wykład_4

Przykłady prezentowane w trakcie Wykładu 4 dla przedmiotów:

W celu przygotowania raportu w postaci pliku html za pomoca narzędzia Publish, w skrypcie zakomentowano linie zawierające polecenia powodujące błąd uniemożliwiający dlsza realizację kodu.

Semestr zimowy. Rok akad. 2017/18 Prowadzący: dr inż. Beata Leśniak-Plewińska

Contents

Typy liczbowe

clear all
help datatypes
  Data types and structures.
 
  Data types (classes)
    double          - Convert to double precision.
    logical         - Convert numeric values to logical.
    cell            - Create cell array.
    struct          - Create or convert to structure array.
    table           - Create a table from workspace variables.
    single          - Convert to single precision.
    uint8           - Convert to unsigned 8-bit integer.
    uint16          - Convert to unsigned 16-bit integer.
    uint32          - Convert to unsigned 32-bit integer.
    uint64          - Convert to unsigned 64-bit integer.
    int8            - Convert to signed 8-bit integer.
    int16           - Convert to signed 16-bit integer.
    int32           - Convert to signed 32-bit integer.
    int64           - Convert to signed 64-bit integer.
    categorical     - Create a categorical array.
    inline          - Construct INLINE object.
    function_handle - Function handle array.
    javaArray       - Construct a Java Array object.
    javaMethod      - Invoke a Java method.
    javaObject      - Invoke a Java object constructor.
    javaMethodEDT   - Invoke a Java method on the Swing Event Dispatch Thread.
    javaObjectEDT   - Invoke a Java object constructor on the Swing Event Dispatch Thread.
 
    cast            - Cast a variable to a different data type or class.
 
  Class determination functions.
    isnumeric       - True for numeric arrays.
    isfloat         - True for floating point arrays, both single and double.
    isinteger       - True for arrays of integer data type.
    islogical       - True for logical array.
 
    iscom           - true for COM/ActiveX objects.
    isinterface     - true for COM Interfaces.
 
  Cell array functions.
    cell            - Create cell array.
    celldisp        - Display cell array contents.
    cellplot        - Display graphical depiction of cell array.
    cell2mat        - Convert the contents of a cell array into a single matrix.
    mat2cell        - Break matrix up into a cell array of matrices.
    num2cell        - Convert numeric array into cell array.
    deal            - Deal inputs to outputs.
    cell2struct     - Convert cell array into structure array.
    struct2cell     - Convert structure array into cell array.
    iscell          - True for cell array.
 
  Array functions.
    arrayfun        - Apply a function to each element of an array.
    cellfun         - Apply a function to each cell of a cell array.
    structfun       - Apply a function to each field of a scalar structure.
 
  Structure functions.
    struct          - Create or convert to structure array.
    fieldnames      - Get structure field names.
    getfield        - Get structure field contents.
    setfield        - Set structure field contents.
    rmfield         - Remove fields from a structure array.
    isfield         - True if field is in structure array.
    isstruct        - True for structures.
    orderfields     - Order fields of a structure array.
 
  Table functions.
    table           - Create a table from workspace variables.
    array2table     - Convert matrix to table.
    cell2table      - Convert cell array to table.
    struct2table    - Convert structure array to table.
    table2array     - Convert table to a homogeneous array.
    table2cell      - Convert table to cell array.
    table2struct    - Convert table to structure array.
    istable         - True for tables.
 
  Categorical functions.
    categorical     - Create a categorical array.
    iscategorical   - True for categorical arrays.
 
  Function handle functions.
    @               - Create function_handle; use "help function_handle".
    func2str        - Construct a character vector representing a function name from a function handle.
    str2func        - Construct a function_handle from a function name.
    functions       - List functions associated with a function_handle.
 
  Byte manipulation functions.
    swapbytes       - Swap byte ordering, changing endianness.
    typecast        - Convert datatypes without changing underlying data.
 
  Object oriented programming functions.
    class           - Create object or return object class.
    classdef        - Define a new MATLAB class.
    struct          - Convert object to structure array.
    methods         - Display class method names.
    methodsview     - View names and properties of class methods.
    properties      - Display class property names.
    events          - Display class event names.
    enumeration     - Display class enumerated value names.
    superclasses    - Display names of the superclasses of a given class.
    isa             - True if object is a given class.
    isjava          - True for Java object arrays
    isobject        - True for MATLAB objects.
    inferiorto      - Inferior class relationship.
    superiorto      - Superior class relationship.
    substruct       - Create structure argument for SUBSREF or SUBSASGN.
    ismethod        - True if method of an object.
    isprop          - Returns true if the property exists
    metaclass       - Metaclass for MATLAB class
 
    loadobj         - Called when loading an object from a .MAT file.
    saveobj         - Called when saving an object to a .MAT file.

Precyzja dla typów liczbowych zmiennoprzecinkowych

eps('double')
ans =
   2.2204e-16
eps('single')
ans =
  single
  1.1921e-07
eps(1000)
ans =
   1.1369e-13
eps(single(1000))
ans =
  single
  6.1035e-05

Wyświetlanie wartości liczbowych w Oknie Poleceń

help format
 FORMAT Set output format.
    FORMAT with no inputs sets the output format to the default appropriate
    for the class of the variable. For float variables, the default is
    FORMAT SHORT.
 
    FORMAT does not affect how MATLAB computations are done. Computations
    on float variables, namely single or double, are done in appropriate
    floating point precision, no matter how those variables are displayed. 
    Computations on integer variables are done natively in integer. Integer
    variables are always displayed to the appropriate number of digits for
    the class, for example, 3 digits to display the INT8 range -128:127.
    FORMAT SHORT and LONG do not affect the display of integer variables.
 
    FORMAT may be used to switch between different output display formats
    of all float variables as follows:
      FORMAT SHORT     Scaled fixed point format with 5 digits.
      FORMAT LONG      Scaled fixed point format with 15 digits for double
                       and 7 digits for single.
      FORMAT SHORTE    Floating point format with 5 digits.
      FORMAT LONGE     Floating point format with 15 digits for double and
                       7 digits for single.
      FORMAT SHORTG    Best of fixed or floating point format with 5 
                       digits.
      FORMAT LONGG     Best of fixed or floating point format with 15 
                       digits for double and 7 digits for single.
      FORMAT SHORTENG  Engineering format that has at least 5 digits
                       and a power that is a multiple of three
      FORMAT LONGENG   Engineering format that has exactly 16 significant
                       digits and a power that is a multiple of three.
 
    FORMAT may be used to switch between different output display formats
    of all numeric variables as follows:
      FORMAT HEX     Hexadecimal format.
      FORMAT +       The symbols +, - and blank are printed 
                     for positive, negative and zero elements.
                     Imaginary parts are ignored.
      FORMAT BANK    Fixed format for dollars and cents.
      FORMAT RAT     Approximation by ratio of small integers.  Numbers
                     with a large numerator or large denominator are
                     replaced by *.
 
    FORMAT may be used to affect the spacing in the display of all
    variables as follows:
      FORMAT COMPACT Suppresses extra line-feeds.
      FORMAT LOOSE   Puts the extra line-feeds back in.
 
    Example:
       format short, pi, single(pi)
    displays both double and single pi with 5 digits as 3.1416 while
       format long, pi, single(pi)
    displays pi as 3.141592653589793 and single(pi) as 3.1415927.
 
       format, intmax('uint64'), realmax
    shows these values as 18446744073709551615 and 1.7977e+308 while
       format hex, intmax('uint64'), realmax
    shows them as ffffffffffffffff and 7fefffffffffffff respectively.
    The HEX display corresponds to the internal representation of the value
    and is not the same as the hexadecimal notation in the C programming
    language.
 
    See also DISP, DISPLAY, ISNUMERIC, ISFLOAT, ISINTEGER.

    Reference page in Doc Center
       doc format


Format domyślny (short) i zmiana formatu

pi
ans =
    3.1416
format('long')
pi
ans =
   3.141592653589793

Przywrócenie domyślnego formatu wyświetlania wyników w Oknie Poleceń

format('short')

Wyświetlanie liczb całkowitych

factorial(15)
ans =
   1.3077e+12

Wyświetlanie tablicy o elementach znacznie się różniących co do wartości

x = [25 357346 2013826793]
x =
   1.0e+09 *
    0.0000    0.0004    2.0138

Wady i zalety typów liczbowych innych niż double

Ograniczenie miejsca w pamięci niezbędnego do przechowywanie danej zmiennej

clear all
a = zeros(100000,1);
b = int8(zeros(100000,1));
c = int16(zeros(100000,1));
whos
  Name           Size             Bytes  Class     Attributes

  a         100000x1             800000  double              
  b         100000x1             100000  int8                
  c         100000x1             200000  int16               

Problemy z użyciem niektóych funkcji

a = int16(3);
% b=sqrt(a) % poniższe linie zakomentowano z powodu błedu
% c = exp(a)

Zakresy wartości liczbowych dla liczbowych typów danych

[intmax('uint8') intmin('uint8')]
ans =
  1×2 uint8 row vector
   255     0
[intmax('int16') intmin('int16')]
ans =
  1×2 int16 row vector
    32767   -32768
realmax('single')
realmin('single')
ans =
  single
  3.4028e+38
ans =
  single
  1.1755e-38
realmax('double')
realmin('double')
ans =
  1.7977e+308
ans =
  2.2251e-308
realmin
ans =
  2.2251e-308

Konsekwencja przekroczenia zakresu dopuszczalnych wartości

clear
a = 250 + 10
a =
   260
b = uint8(250 + 10)
b =
  uint8
   255
whos
  Name      Size            Bytes  Class     Attributes

  a         1x1                 8  double              
  b         1x1                 1  uint8               

Identyfikatory Inf i Nan

clear
1/0
ans =
   Inf
a = [1 2 3]
b = [2 0 1]
a./b
a =
     1     2     3
b =
     2     0     1
ans =
    0.5000       Inf    3.0000
0/0
ans =
   NaN
str2double('2.3')
ans =
    2.3000
str2double('i')
ans =
   0.0000 + 1.0000i
lpi = str2double('pi')
isnan(lpi)
lpi =
   NaN
ans =
  logical
   1

Znaki i łańcuchy znakowe

clear;
s1 = 'hello'
s2 = ' '
s3 = 'world!'
s1 =
    'hello'
s2 =
    ' '
s3 =
    'world!'
s = [s1, s2, s3]
s =
    'hello world!'
size(s)
ans =
     1    12

Tworzenie macierzy złożonej z łańcuchów znakowych

% s = [s1; s2; s3] % zakomentowano z powodu błędu
clear;
s1 = 'hello ';
s2 = '      ';
s3 = 'world!';
s = [s1 ; s2 ; s3]
s =
  3×6 char array
    'hello '
    '      '
    'world!'
size(s)
ans =
     3     6

Identyfikacja typu danych

% Funkcja class

clear;
a = 1:5
b = 'Some String'
a =
     1     2     3     4     5
b =
    'Some String'
class(a)
ans =
    'double'
class(b)
ans =
    'char'

Inne funkcje

isa(a, 'double')
ans =
  logical
   1
isa(a, 'char')
ans =
  logical
   0
ischar(b)
ans =
  logical
   1

Typ logiczny

clear
v = true;
disp(v)
class(v)
   1
ans =
    'logical'
a = rand([1,5])
b = a>0.5
class(b)
a =
    0.8147    0.9058    0.1270    0.9134    0.6324
b =
  1×5 logical array
   1   1   0   1   1
ans =
    'logical'

Komórki i tablice komórkowe

Tworzenie tablic komórkowych

clear
a = {'Hi', ' ', 'World!'}
a =
  1×3 cell array
    'Hi'    ' '    'World!'
whos
  Name      Size            Bytes  Class    Attributes

  a         1x3               354  cell               

Dostęp do elementó tablicy komórkowej

clear
names = {'Bloggs', 'San', 'Andersen'}
first_cell = names(1)
rest_of_cells = names(2:3)
third_string = names{3}
names =
  1×3 cell array
    'Bloggs'    'San'    'Andersen'
first_cell =
  cell
    'Bloggs'
rest_of_cells =
  1×2 cell array
    'San'    'Andersen'
third_string =
    'Andersen'
whos
  Name               Size            Bytes  Class    Attributes

  first_cell         1x1               124  cell               
  names              1x3               370  cell               
  rest_of_cells      1x2               246  cell               
  third_string       1x8                16  char               

Tablice komórkowe zmiennych różnych typów

mixedData = {'string', uint8(10), true, [22 23 24 pi]}
mixedData =
  1×4 cell array
    'string'    [10]    [1]    [1×4 double]
class(mixedData{1})
class(mixedData{2})
class(mixedData{3})
class(mixedData{4})
ans =
    'char'
ans =
    'uint8'
ans =
    'logical'
ans =
    'double'

Nawiasy - podsumowanie

Tworzenie tablic

numArray = [5 62.7 3]
charArray = ['a' 'b' 'c']
numArray =
    5.0000   62.7000    3.0000
charArray =
    'abc'
sameTypeCells = {'Once' ' upon' ' a' 'time'}
diffTypeCells = {'Number', 17}
sameTypeCells =
  1×4 cell array
    'Once'    ' upon'    ' a'    'time'
diffTypeCells =
  1×2 cell array
    'Number'    [17]

Uzyskiwanie dostępu do elementów tablicy

y23 = numArray(2:3) % dostęp do drugiego i trzeciego elementu tablicy
class(numArray)
class(y23)
y23 =
   62.7000    3.0000
ans =
    'double'
ans =
    'double'
y2r = sameTypeCells(2) % dostęp do drugiego elementu tablicy
class(sameTypeCells)
class(y2r)
y2r =
  cell
    ' upon'
ans =
    'cell'
ans =
    'cell'
y2c = sameTypeCells{2} % dostęp do drugiego elementu tablicy
class(sameTypeCells)
class(y2c)
y2c =
    ' upon'
ans =
    'cell'
ans =
    'char'

Konwersja pomiędzy róznymi typami

Konwersja pomiędzy typem liczbowym i znakowym

char(66)
ans =
    'B'
double('B')
uint8('B')
ans =
    66
ans =
  uint8
   66

Konwersja pomiedzy typem liczbowym a logicznym

logical(1)
logical(3.5)
logical(-12)
logical(0)
ans =
  logical
   1
ans =
  logical
   1
ans =
  logical
   1
ans =
  logical
   0
double(true)
uint8(true)
double(false)
ans =
     1
ans =
  uint8
   1
ans =
     0

Konwersja typu danych dla tablic

arr = uint8(5:9)
class(arr)
arr =
  1×5 uint8 row vector
   5   6   7   8   9
ans =
    'uint8'
arr = [104 101 108 108 111]
char(arr)
arr =
   104   101   108   108   111
ans =
    'hello'

Automatyczna konwersja typu danych

clear;
x = 70;
str = ['To jest liczba: ' x];
disp(str)
To jest liczba: F

Kowersja pomiędzy liczbą w postaci łańcucha znakowego a reprezentacją liczbową

y = num2str(x)
disp(class(x))
disp(class(y))
y =
    '70'
double
char
str = ['To jest liczba: ' num2str(x)];
disp(str)
To jest liczba: 70
'3.142' + 1
str2double('3.142') + 1
ans =
    52    47    50    53    51
ans =
    4.1420

Typ strukturalny

pacjentA = struct
pacjentA = 
  struct with no fields.
pacjentA.nazwisko = 'Jan Kowalski';
pacjentA.narodowosc = 'PL';
pacjentA.urodzony = 1974;
pacjentA.ID = 74040407123;
pacjentA.plec = 'M';
pacjentA.diagnoza = 'NZK';
pacjentA
pacjentA = 
  struct with fields:

      nazwisko: 'Jan Kowalski'
    narodowosc: 'PL'
      urodzony: 1974
            ID: 7.4040e+10
          plec: 'M'
      diagnoza: 'NZK'
pacjentB = struct('nazwisko','Ewa Nowak', ...
                  'narodowosc','PL', ...
                  'urodzony','1967',...
                  'ID','67122402345',...
                  'plec','K',...
                  'diagnoza','NZK')
pacjentB = 
  struct with fields:

      nazwisko: 'Ewa Nowak'
    narodowosc: 'PL'
      urodzony: '1967'
            ID: '67122402345'
          plec: 'K'
      diagnoza: 'NZK'
disp([pacjentA.nazwisko ' jest z ' pacjentA.narodowosc])
Jan Kowalski jest z PL
pacjentC = struct('nazwisko','Stanisław Piotrowicz','narodowosc','PL','urodzony','1987',...
                  'ID','87011498754','plec','M','diagnoza','cukrzyca')
pacjentD = struct('nazwisko','Erika Mustermann','narodowosc','DE','urodzony','1992',...
                  'ID','','plec','K','diagnoza','ciąża')
pacjentC = 
  struct with fields:

      nazwisko: 'Stanisław Piotrowicz'
    narodowosc: 'PL'
      urodzony: '1987'
            ID: '87011498754'
          plec: 'M'
      diagnoza: 'cukrzyca'
pacjentD = 
  struct with fields:

      nazwisko: 'Erika Mustermann'
    narodowosc: 'DE'
      urodzony: '1992'
            ID: ''
          plec: 'K'
      diagnoza: 'ciąża'
pacjenci = [pacjentA pacjentB pacjentC pacjentD]
pacjenci = 
  1×4 struct array with fields:
    nazwisko
    narodowosc
    urodzony
    ID
    plec
    diagnoza
pacjenci([2 3]).nazwisko
ans =
    'Ewa Nowak'
ans =
    'Stanisław Piotrowicz'
nazwiska = pacjenci([2 3]).nazwisko
nazwiska =
    'Ewa Nowak'
[nazwiskoA nazwiskoB] = pacjenci([2 3]).nazwisko
nazwiskoA =
    'Ewa Nowak'
nazwiskoB =
    'Stanisław Piotrowicz'