Data Type Conversion

Data type conversion allows you to change the data type of variables or arrays. Here's a brief summary of how you can perform data type conversions in MATLAB:

Common Data Type Conversions in MATLAB:

  1. Numeric to String Conversion:

    • num2str: Converts numbers to their string representation.

      matlab
      num = 123.45;
      str = num2str(num); % '123.45'
      
  2. String to Numeric Conversion:

    • str2num: Converts strings to numeric values.

      matlab
      str = '123.45';
      num = str2num(str); % 123.45
      
  3. Array to Cell Array Conversion:

    • num2cell: Converts numeric arrays to cell arrays.

      matlab
      A = [1, 2; 3, 4];
      C = num2cell(A); % {1, 2; 3, 4}
      
  4. Cell Array to Array Conversion:

    • cell2mat: Converts cell arrays to numeric arrays.

      matlab
      C = {1, 2; 3, 4};
      A = cell2mat(C); % [1, 2; 3, 4]
      
  5. Structure to Cell Array Conversion:

    • struct2cell: Converts structures to cell arrays.

      matlab
      S.name = 'John';
      S.age = 30;
      C = struct2cell(S); % {'John'; 30}
      
  6. Logical to Numeric Conversion:

    • double: Converts logical values to double-precision values.

      matlab
      L = true;
      num = double(L); % 1
      
  7. Numeric to Logical Conversion:

    • logical: Converts numeric values to logical values.

      matlab
      num = 1;
      L = logical(num); % true
      

Example:

Here's an example that combines a few of these conversions:

matlab
% Numeric to String
num = 42;
str = num2str(num); % '42'

% String to Numeric
numAgain = str2num(str); % 42

% Array to Cell Array
A = [1, 2; 3, 4];
C = num2cell(A); % {1, 2; 3, 4}

% Cell Array to Array
AAgain = cell2mat(C); % [1, 2; 3, 4]

% Structure to Cell Array
S.name = 'Alice';
S.age = 25;
CStruct = struct2cell(S); % {'Alice'; 25}

% Logical to Numeric
L = false;
numLogical = double(L); % 0

% Numeric to Logical
LAgain = logical(numLogical); % false

% Display the results
disp(['String: ', str]);
disp(['Numeric again: ', num2str(numAgain)]);
disp('Cell array:');
disp(C);
disp('Array again:');
disp(AAgain);
disp('Cell array from structure:');
disp(CStruct);
disp(['Numeric from logical: ', num2str(numLogical)]);
disp(['Logical again: ',