playground_01_primitive_variables - VMinhoto/workshop-matlab GitHub Wiki
Primitive Variables
Numbers
Number type variables store numeric values. By default a numeric variable in Matlab is stored as a double. All Matlab values are seen as arrays. Even if just assign on number it is seen as a 1 value Array.
%Assigning a variable
aVariable=3
%Multiple assignements
variableOne=1; variableTwo=2; variableThree=3;
%Assigning an int
anInt=int16(3)
%Matlab as in-built complex numbers
aComplex=3+5i;
anotherComplex=3+5j %Using i or j as the imaginary key is the same.
%Get real part of a complex number
realPart=real(aComplex)
%Get imaginary part of a complex number
imaginaryPart=imag(aComplex)
%Operations are done as a normal operations is a calculator
%Sum
exampleSum=5+3
%Subtraction
exampleSubtraction=5-3
%Division
exampleDivision=5/3
%Multiplication
exampleMultiplication=5*3
%Power
examplePower=5^3
%Square Root
exampleSqrt=sqrt(5)
%If you forget your variables you can look at the variables space
%or perform the command who
who; %This command will list the variables! Try it!
%If you want some more detail about the variables you can perform whos
whos; %Try it yourself :)
Strings
In Matlab we create stings just by using ' '. If you remember Matlab sees all variables as arrays. This way a String is seen as an array of Chars(Characters).
% assigning to a string variable
aChar = '3'
aString = '333333'
coolString = 'The quick brown fox jumped over the lazy dog'
% get string length (number of characters)
length = length(coolString) % 44
% Matlab slices use (start:stop)
% Remember, Matlab index starts with 1.
index1 = coolString(1) % the letter 'T'
index6 = coolString(6) % the letter 'u'
lastChar = coolString(length(coolString)) % the letter 'g'
coolSlice = coolString(5:23) % the string 'quick brown fox jum'
coolSliceFromStart = coolString(:23) % the string 'The quick brown fox jum'
coolSliceToEnd = coolString(4:length(coolString)) % 'quick brown fox jumped over the lazy dog'
pointlessSlice = coolString(:) % the original string
%concatenation of strings
pp = 'pen pineapple'
ap = 'apple pen'
concatenation = strcat(pp,ap) %pen pineapple apple pen