computação e programação - ulisboap_ap... · joão reis computação e programação 2009 /...

18
Instituto Superior Técnico, Dep. de Engenharia Mecânica - ACCAII Computação e Programação 10ª Aula de Problemas Tópicos Avançados sobre Funções

Upload: lythuy

Post on 24-Nov-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Instituto Superior Técnico,

Dep. de Engenharia Mecânica - ACCAII

Computação e Programação

10ª Aula de Problemas

Tópicos Avançados sobre Funções

João Reis Computação e Programação 2009 / 2010

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.

João Reis Computação e Programação 2009 / 2010

soundvel = @ (Rtemp) 49.02 * sqrt(Rtemp);

Problema 1 Codificação

João Reis Computação e Programação 2009 / 2010

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

João Reis Computação e Programação 2009 / 2010

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;

end

end

outvel = 49.02*sqrt(temp);

Problema 2 Codificação

João Reis Computação e Programação 2009 / 2010

Problema 3

8. Write an anonymous function to implement the following quadratic:

3x2-2x+5. Then, use fplot to plot the function in the range from -6 to

6.

João Reis Computação e Programação 2009 / 2010

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 3 Codificação

João Reis Computação e Programação 2009 / 2010

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.

João Reis Computação e Programação 2009 / 2010

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;

end

if nargout == 3

% return the year also

varargout{2} = rest(2:end);

end

Problema 4 Codificação

João Reis Computação e Programação 2009 / 2010

Problema 5

20. A recursive definition of an where a is an integer and n is a

non-negative integer is:

an = 1 if n == 0

a x an-1 if n > 0

Write a recursive function called mypower which receives a and n

and returns the value of an by implementing the above definition.

NOTE: The program should NOT use ^ operator anywhere; this is to

be done recursively instead! Test the function.

João Reis Computação e Programação 2009 / 2010

function res = mypower(a,n)

% recursively finds a^n

if n == 0

res = 1;

else

res = a * mypower(a, n-1);

end

Problema 5 Codificação

João Reis Computação e Programação 2009 / 2010

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

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.

( 1) ( )y k y k

x

João Reis Computação e Programação 2009 / 2010

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, independentemente 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.

João Reis Computação e Programação 2009 / 2010

function [y varargout] = funcao_e_derivadas(x, varargin)

derivada_aprox = @(yy, step_x) (yy(2:end)-yy(1:end-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.');

end

plot(x,y,'b'), hold on

Problema 6 Codificação

João Reis Computação e Programação 2009 / 2010

if no >= 2,

if length(x) < 2

error('Estimar dy/dx requer no mínimo 2 pontos.')

end

dy_dx = derivada_aprox(y, x(2)-x(1));

varargout{1} = dy_dx;

plot(x(1:end-1), dy_dx, 'r');

if no == 3,

if length(x) < 3

error('Estimar d2y/dx2 requer no mínimo 3 pontos.')

end

d2y_dx2 = derivada_aprox(dy_dx, x(2)-x(1));

varargout{2} = d2y_dx2;

plot(x(1:end-2), d2y_dx2, 'm');

elseif no > 3,

error('Demasiados argumentos de saida.');

end

end

hold off

Problema 6 Codificação

João Reis Computação e Programação 2009 / 2010

Exercícios Propostos

16

[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.

João Reis Computação e Programação 2009 / 2010

Exercícios Propostos

17

[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 = π r2 where r is

the radius) and H is the height. Use a nested function to calculate A.

João Reis Computação e Programação 2009 / 2010

Referências

18

• [Livro 1]

Capítulo 9 de “Matlab: A Practical Introduction to Programming andProblem Solving”, Stormy Attaway (2009) Elsevier.