70 likes | 167 Views
CS 170 – Intro to Scientific and engineering Programming . Character Arrays . N umeric arrays ~ double arrays ~ matrices C haracter array or char or strings Use the single quote ’ to create basic character arrays Example >> A = ’Dr. X is the teacher’; >> size(A) >> class(A) >> whos.
E N D
Character Arrays • Numeric arrays ~ double arrays ~ matrices • Character array or char or strings • Use the single quote ’ to create basic character arrays • Example >> A = ’Dr. X is the teacher’; >> size(A) >> class(A) >> whos
Character Arrays • How much memory does a character array use? • Example: Recall that a double array uses 8 bytes/element >> B = rand(1,19); >> A = ’Dr. X is the teacher’; >> size(A) >> size(B) >> whos • So, character arrays only use 2 bytes/element.
Numeric Values of Character Arrays • A character array = numberic array = integer values • You can convert a character array into its numeric array using the command DOUBLE. • You can convert a double array with integer values into its equivalent character array using the CHAR command. >> double([’Class is half over’]) >> v=[98 101 32 112 97 116 105 101 110 116] >> char(v)
Referencing a CHAR array • Use integer indices • Example >> A = ’Dr. X is the teacher’; >> A(1:4) >> A(end:-1:1) >> A([5 8 12])
Concatenating CHAR arrays • Use square brackets to stack • Example >> str1 = ’Math is fun, ’; >> str2 = ’but Engineering is better!’; >> str3 = [str1 str2] >> size(str1) >> size(str2) >> size(str3) >> str4 = [str1 ; ’ ’ str2]; >> disp(str4)