0% found this document useful (0 votes)
4 views

ENGR113 - Lecture 5-Creating Arrays-B

The document provides an introduction to MATLAB's built-in functions for handling arrays, including functions like length, size, and reshape. It also explains character arrays and string arrays, detailing how to create, manipulate, and index them, along with examples of their usage. Additionally, it covers string operations such as concatenation, finding and replacing substrings, and handling different lengths of text within arrays.

Uploaded by

ahenxk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

ENGR113 - Lecture 5-Creating Arrays-B

The document provides an introduction to MATLAB's built-in functions for handling arrays, including functions like length, size, and reshape. It also explains character arrays and string arrays, detailing how to create, manipulate, and index them, along with examples of their usage. Additionally, it covers string operations such as concatenation, finding and replacing substrings, and handling different lengths of text within arrays.

Uploaded by

ahenxk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Introduction to Computing using MATLAB

ENGR 113

Creating Arrays-B
(Textbook Chapter 2)
Spring 2022
Instructor Name

1
Built-in Functions for Handling Arrays
MATLAB has many built-in functions for working with arrays. Some
common ones are:
• length(v): number of elements in a vector.
• size(A): number of rows and columns in a matrix or vector.
• reshape(A,m,n): changes number of rows and columns of a
matrix or vector while keeping total number of elements the same.
For example, changes a 4x4 matrix to a 2x8 matrix.

For more functions, use Help to search for the section labeled "Matrices
and Arrays“.
L = length(X) returns the length of the largest array dimension in X.
The length of an empty array is zero.

Find the length of a 3-by-7 matrix of zeros.


>> X = zeros(3,7);
>> L = length(X)
L = 7

Create a random matrix and separately return number of rows & columns.
>> A = rand(4,3);
How can we create a random
>> [numRows, numCols] = size(A) matrix of integers?
numRows = 4
numCols = 3
The reshape function changes the size and shape of an array, as long as
the number of elements in each shape are the same.

For example, reshape a 3-by-4 matrix to a 2-by-6 matrix.


>> A = [1 4 7 10; 2 5 8 11; 3 6 9 12] %3×4 matrix
A =
1 4 7 10
2 5 8 11
3 6 9 12
>> B = reshape(A,2,6) %2×6 matrix
B =
1 3 5 7 9 11
2 4 6 8 10 12
Text Representation in MATLAB:
Character Arrays & Strings Arrays
There are two ways to represent text in MATLAB: character arrays and
string arrays.
• Both types of arrays can contain letters, digits, symbols, and spaces.
• Both types of arrays can be assigned to variable names, just like
numbers.

MATLAB functions that accept character arrays as inputs also accept string
arrays, and vice versa.
• For a full listing of functions used to manipulate text in character arrays
and string arrays, visit: mathworks.com/help/matlab/characters-and-
strings.html
Character Arrays
A character array is a sequence of characters, just as a numeric array is a
sequence of numbers.
• The characters are stored in the array just like numbers.
• Each character in the array, including a space, is an element with index.
• A one-line character array is a row vector.

Character arrays in MATLAB are commonly used to:


• Specify single pieces of text, such as file names and plot labels.
• Represent data where we need easy access to individual characters.
We create a character array using single quotation marks.
>> C = 'Hello, world'
C =
'Hello, world’

>> police = 'New York''s finest'


police =
New York's finest If the text itself includes single quotes, use
two single quotes within the definition
Character arrays are indexed the same way as vectors and matrices.
• We can read, write, or delete by index.
>> word = 'dale';
>> word(1)
ans = d
>> word(1) = 'v'
word = vale
>> word(end) = []
word = val
>> word(end+1:end+3) = 'ley'
word = valley
For example, you can store a DNA sequence as a character vector.
>> seq = 'GCTAGAATCC';

You can access individual characters or subsets of characters by indexing,


just as you would index into a numeric array.
>> seq(4:6)
ans = 'AGA'

You can concatenate (add text to the end of) a character vector with
square brackets, just as you concatenate other types of arrays.
>> seq = [seq, 'ATTAGAAACC']
Two more equivalent ways:
seq = 'GCTAGAATCCATTAGAAACC'
seq(end+1:end+10) = 'ATTAGAAACC'
seq = append(seq, 'ATTAGAAACC')
>> name = 'Howard the Duck';
>> size(name)
ans =
1 15 Number of elements is number of characters in the vector

>> names = ['Greg'; 'John']


names = Try to evaluate:
names(2) names(5)
Greg names(2,1) names(1,3)
John
>> size(names)
ans =
2 4 Number of elements is number of characters in the matrix
Problem
4 characters 3 characters
>> names = ['Greg'; 'Sam']???
Error using ==> vertcat
CAT arguments dimensions are not consistent.
CAUSE
As with a numerical matrix, all rows must have the same number of
elements
Solution
Must put in extra characters (usually spaces) by hand so that all rows have
same number of characters
>> names = ['Greg'; 'Sam ']
Greg
Extra space
Sam
Better Solution
MATLAB can solve this problem with the char function, which automatically
pads each line of text on the right with enough spaces so that all lines have
the same number of characters.

of characters, each with different length

>> size(Info) Notice that the function char(T1,T2,T3)


ans = forms a character array containing the text
4 13 from T1,T2,T3 as rows
A variable can be defined as either a number or a character array made
up of the same digits.
• The two variables are not the same even though they appear similar
on the screen.

>> x = 356
x =
356
>> y = '356'
y =
'356'

Here, the variable x can be used in mathematical expressions, whereas


the variable y cannot.
Strings Arrays
A string array is a container for pieces of text. In a string array, each element
stores a sequence of characters.
• The character sequences can have different lengths without padding,
such as "yes" and "no".

You can create a string array by enclosing a piece of text in double quotes.
>> str = "Hello, world"
Try to find:
str = size(str)
"Hello, world"
Though the text "Hello, world" is 12-character long, str itself is a 1-
by-1 string. You can use a string to specify a file name, plot label, or any
other piece of textual information.
You can find the number of characters in each element of a string using the
strlength function.
>> n = strlength(str)
strlength accepts both
n = 12 character and string arrays

If the text itself includes double quotes, use two double quotes within the
definition.
>> str = "They said, ""Welcome!"" and waved."
str =
"They said, "Welcome!" and waved."
To create a 2D string array, you can use square brackets.
>> str = ["Mercury" "Gemini" "Apollo"; Notice the use of spaces and
"Skylab" "Skylab B" "ISS"] semicolons
str =
2×3 string array
Try to find:
"Mercury" "Gemini" "Apollo" size(str)
"Skylab" "Skylab B" "ISS" strlength(str)

To create a string array with no characters, use the function strings.


>> emp_str = strings(2,3)
emp_str =
2×3 string array
Try to find:
size(emp_str)
"" "" "" strlength(emp_str)
"" "" ""
You can read and write to string elements.
>> str(1,2)
ans =
"Gemini"

>> str(2,2) = "Artemis"


str =
2×3 string array
"Mercury" "Gemini" "Apollo"
"Skylab" "Artemis" "ISS"
You can concatenate a string (add text to the end of a string) using two
ways: the append function or the plus operator.
>> name = "Ali "; Notice the space after Ali
surname = "Ahmed";
fullname = name + surname
fullname =
"Ali Ahmed"

>> name = "Ali "; Recall that the append function was also
surname = "Ahmed"; used with character arrays
fullname = append(name, surname)
fullname =
"Ali Ahmed"
We can find and replace all occurrences of a substring using the function
strrep.

>> claim = "This is a good example"; strrep


new_claim = strrep(claim, "good", "great") accepts both
new_claim = character and
"This is a great example" string arrays

Here, we have replaced all occurrences of “good” with “great” in the string
claim and stored the output in a new string named new_claim
The function strfind(TEXT,PATTERN) returns the starting indices of
any occurrences of PATTERN in the string TEXT.

>> s = "How much wood would a woodchuck chuck?";


strfind(s,"a") returns 21 strfind
strfind(s,"w") returns 3 10 15 23 accepts both
strfind("a",s) returns [] character and
strfind(s,"wood") returns 10 23 string arrays
strfind(s,"Wood") returns []
strfind(s," ") returns 4 9 14 20 22 32

20

You might also like