Computação e Programação, LEAN, MEMec 1
COMPUTAÇÃO E PROGRAMAÇÃO
1º Semestre 2015/2016MEMec, LEAN
Ficha da Aula Prática 1:
Introdução ao MATLAB
Tópicos da aula:
1. Introdução ao ambiente MATLAB
2. Representação numérica, variáveis, operadores e funções matemáticas 3. Tipos de dados e sua conversão
4. Vectores e matrizes
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: no início de cada aula deve-se mudar a directoria de trabalho do MATLAB 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.
NOTA 4: Para facilitar o seu estudo autónomo, os exercícios que não são aplicáveis ao FreeMat são indicados com /F após o número. Todos os restantes podem ser resolvidos em qualquer dos programas (Matlab, Octave ou FreeMat). Note que as funções (incluindo o comando help) podem não ter exactamente a mesma aparência e forma de utilização no Octave e FreeMat. Consulte a ajuda para esclarecer estes casos.
Exercícios a resolver na aula
Docente Alunos (recomendados) Alunos
Computação e Programação, LEAN, MEMec 2
1. Identificar os componentes da janela do MATLAB
Após inicialização do MATLAB deverá aparecer uma janela semelhante à que se apresenta na figura seguinte.
Figura 1: Janela com o ambiente de trabalho do MATLAB.
1. Menu / Directoria / Barra de ferramentas / Atalhos
Inclui por exemplo os comandos habituais dos programas do Windows, para guardar ficheiros, voltar atrás numa acção, gestão do ambiente de trabalho, etc. Para além de alguns comandos mais específicos do MATLAB, inclui também o caminho (path) da directoria de trabalho actualmente seleccionada.
2. Command Window
É a janela de interacção entre o utilizador e o MATLAB. Nela se podem introduzir e executar imediatamente qualquer tipo de comandos ou instruções.
3. Current Folder
Janela que apresenta o conteúdo da actual directoria de trabalho do MATLAB.
4. Workspace
Lista das entidades (variáveis) actualmente existentes no ambiente de trabalho. Estas variáveis podem ser modificadas, utilizadas em cálculos, ou apagadas. Nos casos em que é possível, o conteúdo da entidade é mostrado junto ao seu identificador (nome).
Menu, Directoria, Barra de ferramentas, Atalhos
Current Folder Command Window
Command History Workspace
Computação e Programação, LEAN, MEMec 3
5. Command History
Apresenta o historial de comandos dados através da Command Window, permitindo repetir facilmente comandos dados, por exemplo, em sessões anteriores. O dia e hora da sessão são registados e representados a verde.
NOTA: A tecla de cursor ↑ permite aceder na própria Command Window ao texto dos últimos comandos introduzidos. É muito útil no caso de ser necessário corrigir algum pequeno detalhe num dos comandos anteriores e repetir a sua execução.
a) A directoria de trabalho
A directoria de trabalho é a directoria onde o MATLAB vai ler e gravar ficheiros se não for dada outra indicação. No caso de ser requirida a leitura de um ficheiro esta será a primeira directoria que será pesquisada, e se o ficheiro for encontrado nesta directoria será lido. Se o ficheiro não for encontrado o MATLAB vai então procurar num conjunto de directorias (MATLAB search path) definidas através da opção Set Path que se encontra no Menu, ou na barra de ferramentas consoante a versão.
Há várias formas de definir a directoria de trabalho. As mais intuitivas são: 1. Navegar na janela Current Folder até encontrar a pasta pretendida
2. Escrever directamente o caminho da directoria, ou seleccionar uma directoria do histórico, na respectiva caixa de texto
ESCOLHA UMA DAS FORMAS, e mude a directoria de trabalho para a sua pen drive.
Ferramentas para navegar pelas
directorias
Clicar na pasta para escrever Clicar na seta para escolher a
partir do histórico Clicar na lupa para pesquisar no computador
Computação e Programação, LEAN, MEMec 4
b) Obter ajuda no MATLAB
Em caso de dificuldade na utilização de uma função ou operador é possível obter ajuda de várias formas: 1. Ajuda resumida na Command Window introduzindo o comando help, ou help seguido do nome
da função desejada.
2. Documentação completa do Matlab através daBarra de ferramentas
3. Acesso à documentação completa de uma função a partir da Command Window introduzindo o
comando doc seguido do nome da função desejada.
Aceder directamente à documentação Pesquisar conteúdo na documentação Clicar para escolher a forma de ajuda desejada
Computação e Programação, LEAN, MEMec 5
2. Representação numérica, variáveis, operadores e funções matemáticas
1. Create a variable, myage, and store your age in it. Subtract one from the value of the variable.
Add two to the value of the variable.
3. /F Explore the format command in more detail. Use help format to find options. Experiment with
format bank to display dollar values.
4. /F Find a format option that would result in the following output format:
>> 5/16 + 2/7 ans =
67/112
5. Think about what the results would be for the following expressions, and then type them to
verify your answers.
25 / 4 * 4 3 + 4 ^ 2 4 \ 12 + 4 3 ^ 2
(5 – 2) * 3
6. Create a variable, pounds, to store a weight in pounds. Convert this to kilograms and assign the
result to a variable kilos. The conversion factor is 1 kilogram = 2.2 pounds.
. The combined resistance RT of three resistors R1, R2, and R3 in parallel is given by
Create variables for the three resistors and store values in each, and then calculate the combined resistance.
8. Create a variable ftemp to store a temperature in degrees Fahrenheit (F). Convert this to degrees
Celsius and store the result in a variable ctemp. The conversion factor is C = (F – 32) * 5/9.
9. The function sin calculates and returns the sine of an angle in radians. Use help elfun to find the
name of the function that returns the sine of an angle in degrees. Verify that calling this function and passing 90 degrees to it results in 1.
10. A vector can be represented by its rectangular coordinates x and y or by its polar coordinates r
and θ. The relationship between them is given by the equations: x = r * cos(θ)
y = r * sin(θ)
Assign values for the polar coordinates to variables r and theta. Then, using these values, assign the corresponding rectangular coordinates to variables x and y.
Computação e Programação, LEAN, MEMec 6
12. Use help elfun or experiment to answer the following questions:
a) Is fix(3.5) the same as floor(3.5)?
b) Is fix(3.4) the same as fix(-3.4)?
c) Is fix(3.2) the same as floor(3.2)?
d) Is fix(-3.2) the same as floor(-3.2)?
e) Is fix(-3.2) the same as ceil(-3.2)?
13. Find MATLAB expressions for the following:
3. Tipos de dados e sua conversão
14. /F Use intmin and intmax to determine the range of values that can be stored in the types int32 and int64.
15. /F Are there equivalents to intmin and intmax for real number types? Use help to find out.
16. Store a number with a decimal place in a double variable (the default). Convert the value of that
variable to the type int32 and store the result in a new variable.
19. In the ASCII character encoding, the letters of the alphabet are in order: ‘a’ comes before ‘b’
and also ‘A’ comes before ‘B’, for example. However, which comes first: lower- or uppercase letters?
20. Shift the string ‘xyz’ up in the character encoding by two characters.
4. Trabalhar com matrizes
25. Using the colon operator and the transpose operator, create a column vector that has the
values –1 to 1 in steps of 0.2.
26. Write an expression that refers to only the odd numbered elements in a vector, regardless of
the length of the vector. Test your expression on vectors that have both an odd and even number of elements.
28. Using colon operators for the rows, create the matrix:
7 6 5 3 5 7
Computação e Programação, LEAN, MEMec 7
31. Find an efficient way to generate the following matrix:
mat =
7 8 9 10 12 10 8 6
Then, give expressions that will, for the matrix mat,
a) Refer to the element in the first row, third column
b) Refer to the entire second row
c) Refer to the first two columns
32. Create a matrix variable, mymat, which stores the following:
mymat = 2 5 8 7 5 3
Using this matrix, find a simple expression that will transform the matrix into each of the following:
2 7 5 5 8 3 8 5 2 3 5 7 8 3 5 5 2 7 2 5 8 2 5 8 7 5 3 7 5 3
33. Create a 4 × 2 matrix of all zeros and store it in a variable. Then, replace the second row in the
matrix with a 3 and a 6. (hint: use zeros instead of creating the matrix explicitly)
34. Create a vector, x, which consists of 20 equally spaced points in the range from – π to + π.
Create a y vector that is sin(x). (hint: use linspace instead of the colon operator)
35. Create a 3 × 5 matrix of random integers, each in the range from –5 to 5. Get the sign of every
element. (hint: use randi to generate the matrix)
36. Create a 4 × 6 matrix of random integers, each in the range from –5 to 5; store it in a variable.
Create another matrix that stores for each element the absolute value of the corresponding element in the original matrix.
38. The built-in function clock returns a vector that contains six elements: the first three are the
current date (year, month, day) and the last three represent the current time in hours, minutes, and seconds. The seconds is a real number, but all others are integers. Store the result from clock in a variable called myc. Then, store the first three elements from this variable in a variable called
today, and the last three elements in a variable called now. Use the fix function on the vector
Computação e Programação, LEAN, MEMec 8
5. Challenge
Referências
Capítulo 1 do livro de apoio: “Matlab: A Practical Introduction to Programming and Problem
Solving”, (exercicios da 2ª edição).
Apresentações das AT 2 e AT 3
Nível Exercício
1
Crie as variáveis a, b e c, com os valores adequados e utilize a fórmula resolvente
na Command Window para encontrar as raízes do polinómio: 5x2+3x-1
1
21. Using the colon operator, create the following vectors
3 4 5 6
1.0000 1.5000 2.0000 2.5000 3.0000 5 4 3 2
1 Crie uma variável do tipo char que contenha a palavra Institoto, depois corrija a variável modificando apenas o elemento correspondente à letra que está errada. 2
Crie uma variável do tipo char chamada meu_nome e atribua-lhe uma string com o seu primeiro nome em letras minúsculas (sem acentuação). Utilize uma operação aritmética para converter o valor da variável para maíusculas.
2 Utilize o resultado da divisão inteira, e o resto da mesma, para converter o valor
211 para base binária e para base hexadecimal.
3
27. Create a vector variable, vec; it can have any length. Then, write assignment
statements that would store the first half of the vector in one variable and the second half in another. Make sure that your assignment statements are general, and work whether vec has an even or odd number of elements (hint: use a rounding function such as fix).
3
Considere a seguinte matriz formada pelas submatrizes indicadas pelos quadrados: 1 2 3 5 7 7
4 5 6 5 8 8 7 8 9 1 1 1 0 0 0 1 1 1
Crie variáveis para cada uma das submatrizes com os valores dados, e depois forme a matriz total por concatenação das submatrizes (nota: pode ser feito numa única instrução).