Lecture 3 Sept 3 Complete Chapter 3 Exercises quiz
String operations >> length(greeting) ans = 5 >> strcmp(greeting, ‘hello!’) Ans = 0 ans = 1 if the Boolean expression is true, 0 else. strcmp compares two strings. Strings are case-sensitive. strcat concatenates (glues) strings
String operations strcmp(w1, w2) returns 1 (0) if the strings w1 and w2 are the same. Example: >> a = 'word'; >> b = ['wo', 'rd']; >> strcmp(a, b) ans = 1 >> a == b ans =
String operations strcat (w1, w2) concatenates the strings w1 and w2. Example: >> a = ‘this ’, b = ‘word'; >> c = strcat(a, b); >> c C = ‘thisword’ Strcat removes trailing blanks in the first argument. To avoid this removal, we can use: > c = [a, b];
In general, arrays can be merged using [ ] operation:
String operations A string is stored as a vector of (ASCII) characters. Example: >> str = 'abcdxyz'; >> str+0 ans = ASCII for ‘a’ is 97, for z it is = 122.
Collections of numbers and plotting Two ways to create a vector:
Creating a table of x and y values for plotting A common task is to create the data showing how a variable Y (temp) changes with another variable X (time). Example:
Plot of time vs. temp
Plotting graphs by mathematical relation
Boolean expressions Relational operators:, >=, ~=, == etc. Boolean connectives: & (and) | (or) ~ (not) xor (exclusive or) all any 1 represents TRUE, 0 represents FALSE
Boolean expressions Exercise: Write a one-line statement in MATLAB that returns the number of non- negative members in an array A.
Boolean expressions Exercise: Write a one-line statement in MATLAB that returns the number of non- negative members in an array A. Answer: sum (c >= 0)
Chapter 3 – solutions to some exercises and discussions Dicussion 3.1:
Exercise 3.1: sum(2.^(0 : 4)) Exercise 3.5:
Exercise 3.12:
Exercise 3.12: How many leap years are between 1780 and 2832, inclusive? Recall the definition of a leap year. Exercise 3.8. Write the MATLAB version of the boolean statement a <= b <= c.
Solution to Exercise 3.12: