COMPUTAÇÃO E PROGRAMAÇÃO 1º Semestre 2015/2016 MEMec, LEAN Ficha da Aula Prática 6: Cadeias de caracteres (strings). Estruturas de dados (structures). Sumário das tarefas e objectivos da aula: 1. Utilizar as funções pré-definidas que realizam processamento de strings. 2. Criar e utilizar estruturas com informação organizada por campos. 3. Criar e utilizar vectores de estruturas. NOTA 1: Durante a resolução dos exercícios deverá consultar as apresentações das aulas teóricas, e/ou o livro de apoio da disciplina. NOTA 2: antes de começar cada aula deve-se mudar a directoria de trabalho para uma directoria na pen-drive do aluno, isto garante que o aluno ficará com todos os ficheiros que sejam eventualmente criados durante a aula. Exercícios a resolver na aula Docente Alunos (recomendados) Alunos 1.2, 1.18, 2.11 1.16, 1.20. 2.21 Challenge Computação e Programação, LEAN, MEMec 1
1. Exercícios sobre cadeias de caracteres (strings) 2. Write a function that will receive a name and department as separate strings and will create and return a code consisting of the first two letters of the name and the last two letters of the department. The code should be uppercase letters. For exemple: >> namedept('robert','mechanical') ROAL 8. Write a script that will generate a random integer, ask the user for a field width, and print the random integer with the specified field width. The script will use sprintf to create a string such as 'The # is %4d\n' (if, for example, the user entered 4 for the field width), which is then passed to the fprintf function. In order to print (or create a string using sprintf) either the % or \ character, there must be two of them in a row. 11. The functions that label the x and y axes and title on a plot expect string arguments. These arguments can be string variables. Write a script that will prompt the user for an integer n, then create an x vector with integer values from 1 to n, a y vector that is x^2, and then plot with a title that says x^2 with n values where the value of n is actually in the title. 16. Either in a script or in the Command Window, create a string variable that stores a string in which numbers are separated by the character +, for example 12+3+45+2. Create a vector of the numbers, and then get the sum (e.g., for the example given it would be 62 but the solution should be general). 18. In cryptography, the intended message sometimes consists of the first letter of every word in a string. Write a function crypt that will receive a string with the encrypted message and return the message. >> estring = 'The early songbird tweets'; >> m = crypt(estring) m = Test 20. Words in a sentence variable (just a string variable) called mysent are separated by / s instead of blank spaces. For example, mysent might have this value: 'This/is/not/quite/right'. Write a function slashtoblank that will receive a string in this form and will return a string in which the words are separated by blank spaces. This should be general and work regardless of the value of the argument. No loops are allowed in this function; the built-in string function(s) must be used. >> mysent = 'This/is/not/quite/right'; >> newsent = slashtoblank(mysent) newsent = This is not quite right 22. A filename is supposed to be in the form filename.ext. Write a function that will determine whether a string is in the form of a name followed by a dot followed by a three-character extension, or not. The function should return 1 for logical true if it is in that form, or 0 for false if not. Computação e Programação, LEAN, MEMec 2
26. Using the functions char and double, you can shift words. For example, you can convert from lowercase to uppercase by subtracting 32 from the character codes: >> orig = 'ape'; >> new = char(double(orig)-32) new = APE >> char(double(new)+32) ape We ve encrypted a string by altering the character codes. Figure out the original string. Try adding and subtracting different values (do this in a loop) until you decipher it: Jmkyvih$mx$syx$}ixC 2. Exercícios sobre estruturas de dados (structures) 11. Write the code in MATLAB that would create the following data structure, and put the following values into the variable: experiments num code weights Computação e Programação, LEAN, MEMec 3 feet inches 1 33 x 200.34 202.45 5 6 2 11 t 111.45 111.11 7 2 The variable is called experiments, which is a vector of structs. Each struct has four fields: num, code, weights, and. The field num is an integer, code is a character, weights is a vector with two values (both of which are double values), and is a struct with fields feet and inches (both of which are integers). Write the statements that would accomplish this, so that typing the following expressions in MATLAB would give the results shown: >> experiments experiments = 1x2 struct array with fields: num code weights >> experiments(2) num: 11 code: 't' weights: [111.4500 111.1100] : [1x1 struct]
>> experiments(1). feet: 5 inches: 6 9. A complex number is a number of the form a + ib, where a is called the real part, b is called the imaginary part, and i = -1. Write a script that prompts the user separately to enter values for the real and imaginary parts, and stores them in a structure variable. It then prints the complex number in the form a + ib. The script should just print the value of a, then the string '+ i', and then the value of b. For example, if the script is named compnumstruct, running it would result in: >> compnumstruct Enter the real part: 2.1 Enter the imaginary part: 3.3 The complex number is 2.1 + i3.3 (Note: This is just a structure exercise; MATLAB can handle complex numbers automatically as will be seen in Chapter 14.) 14. A script stores information on potential subjects for an experiment in a vector of structures called subjects. The following show an example of what the contents might be: >> subjects subjects = 1x3 struct array with fields: name sub_id weight >> subjects(1) name: 'Joey' sub_id: 111 : 6.7000 weight: 222.2000 For this particular experiment, the only subjects who are eligible are those whose or weight is lower than the average or weight of all subjects. The script will print the names of those who are eligible. Create a vector with sample data in a script, and then write the code to accomplish this. Don t assume that the length of the vector is known; the code should be general.222 20. Quality control involves keeping statistics on the quality of products. A company tracks its products and any failures that occur. For every imperfect part, a record is kept that includes the part number, a character code, a string that describes the failure, and the cost of both labor and material to fix the part. Create a vector of structures and create sample data for this company. Write a script that will print the information from the data structure in an easy-to-read format. 21. Create a data structure to store information on the planets in our solar system. For every planet, store its name, distance from the sun, and whether it is an inner planet or an outer planet. Computação e Programação, LEAN, MEMec 4
Nível Exercício 1 3. Write a function that will prompt the user separately for a first and last name and will create and return a string with the form last, first. 1 2 3 8. Create a structure variable that would store for a student his or her name, university ID number, and GPA. Print this information using fprintf. 16. Create a nested struct to store a person s name, address, and phone numbers. The struct should have three fields for the name, address, and phone. The address fields and phone fields will be structs. (suponha que o address tem os campos morada e código postal, e que o phone tem telemóvel e residência). 19. Write a function rid_multiple_blanks that will receive a string as an input argument. The string contains a sentence that has multiple blank spaces in between some of the words. The function will return the string with only one blank in between words. For example, >> mystr = 'Hello and ho w are you?'; >> rid_multiple_blanks(mystr) Hello and how are you? Os resultados de um questionário de uma turma podem ser organizados num vector de estruturas como o que se representa no quadro seguinte: estudante 3 numeroid questionario 1 12345 14.0 15.0 16.0 2 67890 11.0 12.0 13.0 3 10111 16.0 16.0 16.0 4 12134 12.0 14.0 16.0 Cada elemento do vector estudante será uma estrutura com dois campos: o valor inteiro numeroid e um vector de valores reais questionario contendo os resultados do questionário. Escreva um script onde cria o vector de estruturas apresentado, e que em seguida calcule e escreva a média do questionário para cada estudante. O resultado deverá ter a seguinte aparência: Estudante Média 12345 15.0 67890 12.0 10111 16.0 12134 14.0 Referências Apresentações das aulas teóricas AT 11 e AT 12. Capítulos 7 e 8 de Stormy Attaway (2012), Matlab: A Practical Introduction to Programming and Problem Solving, Elsevier. Computação e Programação, LEAN, MEMec 5