Computação e Programação 10ª Aula de Problemas Tópicos Avançados sobre Funções Instituto Superior Técnico, Dep. de Engenharia Mecânica - ACCAII
Problema 1 3. The velocity of sound in air is 49.02xT^(1/2) feet per second where T is the air temperature in degrees Rankine. Write an anonymous function that will calculate this. One argument, the air temperature in degrees R, will be passed to the function and it will return the velocity of sound.
Problema 1 Codificação soundvel = @ (Rtemp) 49.02 * sqrt(rtemp);
Problema 2 12. The velocity of sound in air is 49.02xT ^(1/2) feet per second where T is the air temperature in degrees Rankine. Write a function to implement this. If just one argument is passed to the function, it is assumed to be the air temperature in degrees Rankine. If, however, two arguments are passed, the two arguments would be first an air temperature and then a character f for Fahrenheit or c for Celsius (so this would then have to be converted to Rankine). Note: degrees R = degrees F + 459.67 degrees F = 9/5 degrees C + 32
Problema 2 Codificação function outvel = velsound(varargin) n = nargin; if n == 1 % the argument is temp in degrees R temp = varargin{1}; elseif n == 2 % a temp is passed and 'f' or 'c' temp = varargin{1}; unit = varargin{2}; if unit == 'f' % convert from F to R temp = temp + 459.67; elseif unit == 'c' % convert from C to R temp = 9/5*temp + 32 + 459.67; outvel = 49.02*sqrt(temp);
Problema 3 8. Write an anonymous function to implement the following quadratic: 3x 2-2x+5. Then, use fplot to plot the function in the range from -6 to 6.
Problema 3 Codificação quadfn = @ (x) 3*x^2-2*x + 5; fplot(quadfn,[-6 6]) NOTA: Como seria chamada a função fplot para apresentar o valor da função sin no mesmo intervalo?
Problema 4 17. The built-in function date returns a string containing the day, month, and year. Write a function (using the date function) that will always return the current day. If the function call expects two output arguments, it will also return the month. If the function call expects three output arguments, it will also return the year.
Problema 4 Codificação function [day, varargout] = whatdate % Returns the current day and possibly also the % current month and year d = date; % always returns the day [day, rest] = strtok(d, '-'); if nargout > 1 % return the month also [month, rest] = strtok(rest, '-'); varargout{1} = month; if nargout == 3 % return the year also varargout{2} = rest(2:);
Problema 5 20. A recursive definition of a n where a is an integer and n is a non-negative integer is: a n = 1 if n == 0 a x a n-1 if n > 0 Write a recursive function called mypower which receives a and n and returns the value of a n by implementing the above definition. NOTE: The program should NOT use ^ operator anywhere; this is to be done recursively instead! Test the function.
Problema 5 Codificação function res = mypower(a,n) % recursively finds a^n if n == 0 res = 1; else res = a * mypower(a, n-1);
Problema 6 Escreva uma função com as seguintes especificações: Parâmetros de entrada: x vector de pontos (mínimo de 3) func (opcional) handle de função Parâmetros de saída: y vector de pontos dy_dx (opcional) 1ª derivada aproximada de y d2y_dx2 (opcional) 2ª derivada aproximada de y A derivada aproximada pode ser calculada através da expressão y( k 1) y( k) x que deve ser implementada através de uma função anónima. Δx representa o passo do vector x cujos elementos se assumem uniformemente espaçados.
Problema 6 Se a função receber apenas um argumento de entrada deverá devolver e apresentar num gráfico y = x. Se receber os dois argumentos de entrada deve calcular e apresentar y = func(x). Por outro lado, indepentemente do número de argumentos de entrada, se a função for chamada com mais do que um argumento de saída deve estimar, devolver e apresentar no mesmo gráfico as derivadas correspondentes. A função deve também apresentar mensagens de erro caso o número de parâmetros de entrada ou de saída exceda o previsto.
Problema 6 Codificação function [y varargout] = funcao_e_derivadas(x, varargin) derivada_aprox = @(yy, step_x) (yy(2:)-yy(1:-1))/step_x; ni = nargin; no = nargout; if ni == 1 y = x; elseif ni == 2 func = varargin{1}; y = func(x); elseif ni > 2 error('demasiados argumentos de entrada.'); plot(x,y,'b'), hold on
Problema 6 Codificação if no >= 2, if length(x) < 2 error('estimar dy/dx requer no mínimo 2 pontos.') dy_dx = derivada_aprox(y, x(2)-x(1)); varargout{1} = dy_dx; plot(x(1:-1), dy_dx, 'r'); if no == 3, if length(x) < 3 error('estimar d2y/dx2 requer no mínimo 3 pontos.') d2y_dx2 = derivada_aprox(dy_dx, x(2)-x(1)); varargout{2} = d2y_dx2; plot(x(1:-2), d2y_dx2, 'm'); elseif no > 3, error('demasiados argumentos de saida.'); hold off
Exercícios Propostos [Livro 1] (Ver referências noúltimo slide) 5. Create a set of anonymous functions to do length conversions and store them in a file lenconv.mat. Call them descriptive name, e.g cmtoinch to convert from centimeters to inches. 7. Write a function plot2fnhand that will receive two function handles as input arguments, and will display in two Figure Windows plots of these functions, with the function names in the titles. The function will create an x vector that ranges from 1 to n (where n is a random integer in the range from 4 to 10). For example, if the function is called as follows >> plot2fnhand(@sqrt, @exp) and the random integer is 5, the Figure Window 1 would display the sqrt function of x from 1 to 5, and the second Figure Window would display exp(x) for x = 1:5. 16
Exercícios Propostos [Livro 1] (Ver referências noúltimo slide) 10. There is a built-in function function called cellfun that evaluates a function for every element of a cell array. Create a cell array, then call the cellfun function, passing the handle of the length function and the cell array in order to determine the length of every element in the cell array. 18. Write a function to calculate the volume of a cone. The volume V is V = AH where A is the area of the circular base (A = π r 2 where r is the radius) and H is the height. Use a nested function to calculate A. 17
Referências [Livro 1] Capítulo 9 de Matlab: A Practical Introduction to Programming and Problem Solving, Stormy Attaway (2009) Elsevier. 18