Computação e Programação 8ª Aula de Problemas Cell arrays Estruturas Instituto Superior Técnico, Dep. de Engenharia Mecânica - ACCAII
Problema 1 Escreva uma função que recebe um cell array de strings e retorna o cell array ordenado por ordem crescente do comprimento de cada string. Teste a sua função na linha de comando do Matlab.
Problema 1 Análise resumida Parâmetros de entrada: cell_original cell array Parâmetros de saída: cell_ordenado cell array Algoritmo da função ordenacellcomprimento: 1. Criar um vector comprimento conto em cada elemento o comprimento da string do elemento respectivo de cell_original 2. Seja n o numero de elementos de cell_original. Para i variando de n a 1 com passo -1 fazer: a)obter o índice indice_max_comp do elemento de comprimento com valor máximo b) cell_ordenado{i} = cell_original{indice_max_comp} c) comprimento{indice_max_comp} = -1 3
Problema 1 Codificação function cell_ordenado = ordenacellcomprimento(cell_original) for i = 1:length(cell_original) comprimento(i) = length(cell_original{i}); % Pré-alocação do cell array cell_ordenado = cell(1, length(cell_original)); for i = length(cell_original):-1:1 % A função max() devolve o índice no segundo argumento de % saída, max_comp não é realmente necessário [max_comp, indice_max_comp] = max(comprimento); cell_ordenado{i} = cell_original{indice_max_comp}; comprimento(indice_max_comp) = -1;
Problema 2a Escreva um script que crie um cell array chamado cell_info_aluno com informação sobre um aluno e as suas notas na disciplina de C.P. Cada elemento do cell array deve conter os dados conforme o exemplo. Apresente os dados do aluno no formato sugerido, utilize-os para calcular a componente de avaliação escrita da nota final e apresente-a. Número: 12345 Nome: Alberto Manuel Maneirinho Trab.1: Trab.2: Teste 1: Teste 2: Exame 1: Exame 2: 13.5 14.1 17.3 13.7 0.0 15.3 Nota da avaliação escrita: 15.5
Problema 2a Codificação cell_info_aluno = {12345, 'Alberto Manuel Maneirinho', 13.5, 14.1,... 17.3, 13.7, 0.0, 15.3}; fprintf('número: %5d\nNome: %s\n\n', cell_info_aluno{1:2}); fprintf('trab.1: Trab.2: Teste 1: Teste 2: Exame 1: Exame 2:'); fprintf('\n%7.1f%9.1f%10.1f%10.1f%10.1f%10.1f\n',... cell_info_aluno{3:}); media_testes = (cell_info_aluno{3} + cell_info_aluno{4})/2; nota = max(media_testes, cell_info_aluno{8}); fprintf('\nnota da avaliação escrita: %4.1f\n\n', nota);
Problema 2b Repita o problema 2a utilizando agora um objecto da classe struct chamado estrutura_info_aluno. Os campos da estrutura serão denominados: numero nome nota_trab1 nota_trab2 nota_teste1 nota_teste2 nota_exame1 nota_exame2
Problema 2b Codificação estrutura_info_aluno = struct('numero', 12345,... 'nome', 'Alberto Manuel Maneirinho', 'nota_trab1', 13.5,... 'nota_trab2', 14.1, 'nota_teste1', 17.3, 'nota_teste2', 13.7,... 'nota_exame1', 0.0, 'nota_exame2', 15.3); fprintf('número: %5d\nNome: %s\n\n',... estrutura_info_aluno.numero, estrutura_info_aluno.nome); fprintf('trab.1: Trab.2: Teste 1: Teste 2: Exame 1: Exame 2:'); fprintf('\n%7.1f%9.1f%10.1f%10.1f%10.1f%10.1f\n',... estrutura_info_aluno.nota_trab1, estrutura_info_aluno.nota_trab2,... estrutura_info_aluno.nota_teste1, estrutura_info_aluno.nota_teste2,... estrutura_info_aluno.nota_exame1, estrutura_info_aluno.nota_exame2); media_testes = (estrutura_info_aluno.nota_teste1 +... estrutura_info_aluno.nota_teste2)/2; nota = max(media_testes, estrutura_info_aluno.nota_exame2); fprintf('\nnota da avaliação escrita: %4.1f\n\n', nota);
Problema 2c Note ao executar os scripts que os resultados do cálculo da avaliação escrita nas soluções das alíneas 2a e 2b não são iguais. Uma das soluções está incorrecta. Encontre o erro de lógica e corrija-o. Discuta as vantagens e desvantagens de estruturar a informação na forma de um cell array ou na forma de uma struct.
Problema 3 Prete-se criar uma tabela denominada turma em que cada elemento corresponde a uma estrutura de dados similar à do problema 2b. O programa deve fazer a pré-alocação da tabela com espaço para 4 alunos, pedir os dados ao utilizador e posteriormente apresentar os dados de toda a turma. Crie e utilize uma função chamada criaaluno que receba como parâmetros os dados isolados de um aluno e devolva uma struct com a informação organizada. Crie e utilize uma função chamada introduzaluno que peça ao utilizador os dados de um aluno verifique a sua validade e devolva uma struct com a informação organizada. Crie e utilize uma função chamada apresentaaluno que receba uma struct criada pela função criaaluno e apresenta os dados de um aluno no formato: 12345 Alberto Manuel Maneirinho 13.5 14.1 17.3 13.7 0.0 15.3
Problema 3 Codificação function aluno = criaaluno(no, nome, ntrab1, ntrab2, nteste1,... nteste2, nexame1, nexame2) aluno = struct('numero', no, 'nome', nome, 'nota_trab1', ntrab1,... 'nota_trab2', ntrab2, 'nota_teste1', nteste1, 'nota_teste2',... nteste2, 'nota_exame1', nexame1, 'nota_exame2', nexame2);
Problema 3 Codificação introduzaluno.m function aluno = introduzaluno while true nid = input('introduza o número do aluno: '); if nid == round(nid) break disp('o número introduzido não está correcto.'); while true nome_completo = input('introduza o nome completo: ', 's'); if ischar(nome_completo) break disp('o nome introduzido não está correcto.'); %...
Problema 3 Codificação prova = {'1º trabalho', '2º trabalho', '1º teste', '2º teste',... '1º exame', '2º exame'}; for i = 1:6, notas(i) = notavalida(['introduza a nota do ', prova{i}, ': ']); aluno = criaaluno(nid, nome_completo, notas(1), notas(2),... notas(3), notas(4), notas(5), notas(6)); return % Sub-função para introdução e validação das notas function nota = notavalida(mensagem) while true nota = input(mensagem); if isfloat(nota) && nota >= 0 && nota <= 20, break disp('a nota introduzida não é válida.'); return
Problema 3 Codificação function apresentaaluno(aluno) fprintf('%5d%28s%7.1f%9.1f%10.1f%10.1f%10.1f%10.1f\n',... aluno.numero, aluno.nome, aluno.nota_trab1, aluno.nota_trab2,... aluno.nota_teste1, aluno.nota_teste2, aluno.nota_exame1,... aluno.nota_exame2);
Problema 3 Codificação clc, clear all, close all % Pré-alocação de uma turma de 4 alunos turma(4) = criaaluno([],[],[],[],[],[],[],[]); % Introdução dos dados de todos os alunos disp('este programa cria e apresenta uma turma de alunos.') for i = 1: length(turma) turma(i) = introduzaluno; clc; % Apresentação dos dados da turma for i = 1: length(turma) apresentaaluno(turma(i));
Exercícios Propostos [Livro 1] (Ver referências noúltimo slide) 3. Create a 2 x 2 cell array by using the cell function to preallocate and then put values in the individual elements. Then, insert a row in the middle so that the cell array is now 3 x 2. Hint: ext the cell array by adding another row and copying row 2 to row 3, and then modify row 2. 4. Create three cell array variables that store people s names, verbs, and nouns. For example, names = {'Harry', 'Xavier', 'Sue'}; verbs = {'loves', 'eats'}; nouns = {'baseballs', 'rocks', 'sushi'}; Write a script that will initialize these cell arrays, and then print sentences using one random element from each cell array, e.g. Xavier eats sushi. 16
Exercícios Propostos [Livro 1] (Ver referências noúltimo slide) 7. Create a cell array variable that would store for a student his or her name, university id number, and GPA. Print this information. 8. Create a structure variable that would store for a student his or her name, university id number, and GPA. Print this information. 12. Create a data structure to store information about the elements in the periodic table of elements. For every element, store the name, atomic number, chemical symbol, class, atomic weight, and a 7- element vector for the number of electrons in each shell. Create a structure variable to store the information, for example for lithium: Lithium 3 Li alkali_metal 6.94 2 1 0 0 0 0 0 17
Exercícios Propostos [Livro 1] (Ver referências noúltimo slide) 16. Create a nested struct to store a person s name, address, and phone numbers. The struct should have 3 fields for the name, address, and phone. The address fields and phone fields will be structs. 17. Design a nested structure to store information on constellations for a rocket design company. Each structure should store the constellation s name and information on the stars in the constellation. The structure for the star information should include the star s name, core temperature, distance from the sun, and whether it is a binary star or not. Create variables and sample data for your data structure. 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. 18
Exercícios Propostos [Livro 1] (Ver referências noúltimo slide) 22. A manufacturer is testing a new machine that mills parts. Several trial runs are made for each part, and the resulting parts that are created are weighed. A file stores, for every part, the part identification number, the ideal weight for the part, and also the weights from 5 trial runs of milling this part. Create a file in this format. Write a script that will read this information and store it in a vector of structures. For every part print whether the average of the trial weights was less than, greater than, or equal to the ideal weight. 24. Investigate the built-in function cell2struct that converts a cell array into a vector of structs. 25. Investigate the built-in function struct2cell that converts a struct to a cell array. 19
Referências [Livro 1] Capítulo 7 de Matlab: A Practical Introduction to Programming and Problem Solving, Stormy Attaway (2009) Elsevier. 20