matlab ex solutions

3
M-files from Exercise 2 1.) function A = make_A(a,b,c,d) A=zeros(2,2); % Initialize A to all zeros A(1,1) = a; A(1,2) = b; A(2,1) = c; A(2,2) = d; 2.) function y = funplots(x) y = sin(x); % Find sin(x) [x,y] % Print table to the screen % x was supposed to be a column.. plot(x,y,'r--') % Plot your answer xlabel('x') ylabel('sin(x)') 3.) function y = funky(x) y = sqrt((x-2).^2)/pi.*sin(pi*x); % Computations [x,y] % print table to the screen 4.) % Create an 8x8 matrix of my choice A = [1 2 3 4 5 6 7 8; 2 4 6 8 10 12 14 16; 3 6 9 12 15 18 21 24; 4 8 12 16 20 24 28 32; 5 10 15 20 25 30 35 40; 6 12 18 24 30 36 42 48; 7 14 21 28 35 42 49 54; 8 16 24 32 40 48 56 64]; % Set y equal to the first 3 components of row 2 of A y = A(2,1:3); z = A(7,1:3);

Upload: yared4

Post on 15-Jan-2016

221 views

Category:

Documents


0 download

DESCRIPTION

basic matlab

TRANSCRIPT

Page 1: Matlab Ex Solutions

M-files from Exercise 2

1.)

function A = make_A(a,b,c,d)

A=zeros(2,2); % Initialize A to all zerosA(1,1) = a;A(1,2) = b;A(2,1) = c;A(2,2) = d;

2.) function y = funplots(x)

y = sin(x); % Find sin(x)[x,y] % Print table to the screen % x was supposed to be a column..

plot(x,y,'r--') % Plot your answerxlabel('x')ylabel('sin(x)')

3.) function y = funky(x)

y = sqrt((x-2).^2)/pi.*sin(pi*x); % Computations

[x,y] % print table to the screen

4.) % Create an 8x8 matrix of my choiceA = [1 2 3 4 5 6 7 8; 2 4 6 8 10 12 14 16; 3 6 9 12 15 18 21 24; 4 8 12 16 20 24 28 32; 5 10 15 20 25 30 35 40; 6 12 18 24 30 36 42 48; 7 14 21 28 35 42 49 54; 8 16 24 32 40 48 56 64]; % Set y equal to the first 3 components of row 2 of Ay = A(2,1:3);z = A(7,1:3);x = y + z

5.) Make the above file into a function m-file with A as the input.

Page 2: Matlab Ex Solutions

M-Files from Exercise 3

1.) function a = ave(x)

n = length(x); % find the length of xsum = 0; % initialize the sum

for i=1:n sum = sum + x(i); % add up all the components of xend

a = sum/n; % find the average

2.) function s = std_dev(x)

n = length(x); % Find the length of xa = ave(x); % find the averagesum = 0; % Initialize sum

for i=1:n sum = (x(i)-a)^2;ends = (1/(n-1))*sum;

3.) I skipped this one…the idea is implemented in (5.)

4.) and 5.) function [d,i] = double_x(x)

d = x; % initialize variablei=0; % Initialize counterwhile(d < 2*x) d = d +2 i=i+1end

6.) Involves using an if-else loop