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:
-
Numeric to String Conversion:
-
num2str: Converts numbers to their string representation.matlabnum = 123.45; str = num2str(num); % '123.45'
-
-
String to Numeric Conversion:
-
str2num: Converts strings to numeric values.matlabstr = '123.45'; num = str2num(str); % 123.45
-
-
Array to Cell Array Conversion:
-
num2cell: Converts numeric arrays to cell arrays.matlabA = [1, 2; 3, 4]; C = num2cell(A); % {1, 2; 3, 4}
-
-
Cell Array to Array Conversion:
-
cell2mat: Converts cell arrays to numeric arrays.matlabC = {1, 2; 3, 4}; A = cell2mat(C); % [1, 2; 3, 4]
-
-
Structure to Cell Array Conversion:
-
struct2cell: Converts structures to cell arrays.matlabS.name = 'John'; S.age = 30; C = struct2cell(S); % {'John'; 30}
-
-
Logical to Numeric Conversion:
-
double: Converts logical values to double-precision values.matlabL = true; num = double(L); % 1
-
-
Numeric to Logical Conversion:
-
logical: Converts numeric values to logical values.matlabnum = 1; L = logical(num); % true
-
Example:
Here's an example that combines a few of these conversions:
% 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: ',