You are on page 1of 3

11.03.20 E.D.

Numerical Methods in Engineering

Computer Lab Lecture 3 Loops and User Defined Functions in Octave

Recalling For Loop

for i=1:3
x=linspace(0,2*pi,20*i);
y=sin(x);
subplot(1,3,i)
plot(x,y,'ko')
xlabel('x')
ylabel('sin(x)')
title('sin plot')
endfor

Recalling While Loop

n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])

Bank Account (While Loop)

clc, clear
a=1000; %initial account balance
r=0.05; %interest rate/year
bal=a; %account balance
year=0;
while bal<10*a
bal=bal+r*bal;
year=year+1;
disp([year bal])
end

1/3
11.03.20 E.D.

User Defined Functions

function [yy] = My_Function(x,y)


% creates My_function(x,y)=x^2+y^2
%calculates f(x,y)=x^2+y^2
%this part will be shown
%when help
%My_Function is commanded
yy = x.^2+y.^2; % yy need to be defined in function get output
end % ends the function

....
Aritmetic Mean = Geometric Mean = a a a ....a

User Defined Functions (2 output)

function [A,G] = Meanns(X)


%Gives Aritmetic mean and Geometric mean for given vectors
sum=0; %initial value
prod=1; % initial value
n=length(X); % length of X
for i=1:n;
sum=sum + X(i);
prod=prod*X(i);
end
A=sum/n %aritmetic mean
G=prod^(1/n) %geometric mean

Application 1
The inverse of the mathematical constant e can be approximated as
follows:

Write a script that will loop through values of n until the difference
between the approximation and the actual value is less than 0.0001. The
script should then print out the built-in value of e-1 and the
approximation to 4 decimal places, and also print the value of n required
for such accuracy.

2/3
11.03.20 E.D.

Application 2
Write a Matlab Function with two output
First output shows the sign (as-1 0 1) of each element for a matrix.
The second output shows it is even (0) or odd (1)(mod() function can be
used).
The output is an array with same size of input matrix.
Ex input:

Output1

Output2

Application 3
In 3D space, the Cartesian coordinates (x,y,z) can be converted to
spherical coordinates (radius r, inclination ‘θ’ , azimuth ‘Ф’ ) by the
following equations:

Create one function to convert coordinates and another function to print


the results in a same script file.

3/3

You might also like