Вы находитесь на странице: 1из 28

Course Notes Set 5a: COMP1200 Introduction to Computing for Engineers and Scientists MATLAB Programming

Arrays: Vectors and Matrices


Computer Science and Software Engineering Auburn University

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 1 of 59

Arrays: Introduction
What if we had a problem where we needed to average all the grades in a COMP1200 class? How would we store all the grades entered by the user? Using knowledge we have now we could approach this in a couple ways:

1.

We could put all the grades in a data file. Then, open and read the data file each time we want to work with the grades.
Advantage: Disadvantage: Code is relatively simple to write File I/O is very slow

2.

We could declare a variable for each student in the class. Wed then just write an input statement to load each variable.
Advantage: Disadvantage: All the variables are in memory, so its fast Thats a LOT of variables in a class with 100 students!

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 2 of 59

Lets imagine what a program using technique #2 would look like:


% Read in grades in a variable for each grade g1 = input(Enter 1st grade: ); g2 = input(Enter 2nd grade: ); . . . g100 = input(Enter 100th grade: ); % Average grades avg = (g1 + g2 + g3 +...+ g100)/100.0; printf(Average is: %f,avg);

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 3 of 59

Arrays
Now what happens when we add 20 students to the class? We have to add all those new variables! This is not good.

92 g1

72 g2

87 g3

61 g4

89 g5

55 g6

99 g7

. .

86

76

g99 g100

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 4 of 59

Arrays
A program with this many variables can be long and frustrating to use. What if there was a shorthand notation for the many related variables. It would be nice if we could write: %Read in grades disp(Enter 100 grades: ); for i=1:100 gi = input(Enter a grade: ); This will not work because MATLAB would treat gi as a variable and reassign 100 grades to it.

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 5 of 59

Arrays
This is where a MATLAB data structure called an array comes in to help us out. You can visualize the compiler giving you 100 variables arranged in a row:

92
g1

72
g2

87
g3

61
g4

89
g5

55
g6

99
g7

86
g99

76
g100

g(1) g(2) g(3) g(4) g(5) g(6) g(7) g(99) g(100)

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 6 of 59

Array element
Array name Subscript

g(0)
We call each individual variable in an array an element of the array. We give the collection of elements a name, the array name. An array can be given any valid variable name. To get at the individual elements of an array, we number them starting at one, incrementing by one. These numbers are called the subscripts.

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 7 of 59

Arrays: Initializing with values


>> t = [5 4 -2 1 3 9 7 0 -6] % Spaces or commas t = 5 4 -2 1 3 9 7 0 -6 >> t(4) ans = 1 >> t(3:2:9) % Colon Notation to access blocks ans = -2 3 7 -6 >> t(1:5) % Default step is 1 ans = 5 4 -2 1 3 >> t(6:end) ans = 9 7 0 -6
Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 8 of 59

Arrays: Initializing using expressions


>> x = [0 .1*pi .2*pi .3*pi .4*pi .5*pi] x = 0 0.3142 0.6283 0.9425 1.2566

1.5708

>> x = (0:.1:.5)*pi x = 0 0.3142 0.6283

0.9425

1.2566

1.5708

>> x = x * 10 x = 0 3.1416

6.2832

9.4248

12.5664

15.7080

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 9 of 59

Standard Arrays
>> ones(1,5) ans = 1 1

>> count=zeros(1,4) count = 0 0 0 >> count(1) ans = 0 >> par(1:5)=4 par = 4 4

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 10 of 59

Arrays: Initializing
We can also initialize arrays from within our program, this is usually done with a loop:
for k = 1:10 g(k) = k*0.5; This program segment takes each element of an array and sets it to the current value of k. After running, the array looks like:

0.5
g(1)

1.0
g(2)

1.5
g(3)

2.0
g(4)

2.5
g(5)

3.0
g(6)

3.5
g(7)

4.0
g(8)

4.5
g(9)

5.0
g(10)

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 11 of 59

Arrays: Modifying
>> t = [5 4 -2 1 3 9 7 0 -6] t = 5 4 -2 1 3 9 7 >> t(4) = 22 t = 5 4 -2

-6

22

-6

>> g = zeros(1,5) g = 0 0 0 0 0 >> g = [10 20 30 40] g = 10 20 30 40


Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 12 of 59

Arrays: Using In Programs


Using arrays in a program is no different than using normal variables, you just have to remember the array subscript. This is how the compiler will know which array element you want to work with. Lets take an example program that averages the elements of an array:

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 13 of 59

Arrays: Using In Programs


y = [76.0, 35.4, 99.2, 81.0,65.5]; count = numel(y); % returns number of elements sum = 0;

% Total each array element for n = 1:count sum = sum + y(n); 76.0 35.4 99.2 81.0 65.5 end y(1) y(2) y(3) y(4) y(5) % Compute the average average = sum / count ; fprintf('Average = %.2f\n',average);

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 14 of 59

Arrays: Using In Programs


Lets suppose we wanted to print all the values in the array:

for n = 1:count fprintf(%.1f\n',y(n)); end


This prints each element of the array, one per line. 76.0 35.4 99.2 81.0 65.5

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 15 of 59

Arrays: Using In Programs


Similarly, if we wanted to print the numbers on one line: for n = 1:count fprintf(%.1f ',y(n)); end % Add a next line after all numbers fprintf(\n); 76.0 35.4 99.2 81.0 65.5

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 16 of 59

Arrays: Using In Programs


Similarly, if we wanted to print them to a data file : for n = 1:count fprintf(myfile, '%.1f\n', y(n)); end

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 17 of 59

Arrays: Passing To Functions

We have to consider a couple cases when dealing with arrays and functions. Passing A Single Element Passing An Entire Array

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 18 of 59

Arrays: Passing A Single ElementTo Functions


function sum = sumFun( a, b ) ... function body end Now lets suppose in my main program I want to use sumFun, and I want it to operate on a couple of my array elements. Heres how I would call the function: x=[3 2 5 6 2]; i=4; j=1; result = sumFun(x(4), x(1));

or
result = sumFun(x(i), x(j)); So heres the rule: When the arguments are non-array values, the actual arguments sent must be subscripted array elements.
Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 19 of 59

Arrays: Passing An Entire Array To Functions


When passing an entire array to a function, we usually have to supply two parameters: the name of the array being passed and the number of values that will be used. Consider the following initialization: g = [10, 20, 30, 40, 0, 0, 0, 0, 0, 0]; Memory will look like this: 10 20 30 40 0 0 0 0 0 0

g(1) g(2) g(3) g(4) g(5) g(6) g(7) g(8) g(9) g(10)

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 20 of 59

Arrays: Passing An Entire Array To Functions


Now only the first 4 elements of this 10 element array hold values that we care about. What we want to do is tell a function to only consider those values when it operates on the array. Heres how we define the formal parameters for the function: function sum = sumFun( x, n) ... for j = 1:n sum = sum + x(j); end end

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 21 of 59

Arrays: Passing An Entire Array To Functions


To call the function, function sum = sumFun( x, n)

we could do this:
g = [10, 20, 30, 40, 0, 0, 0, 0, 0, 0]; ... result = sumFun(g, 4); % NO subscript

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 22 of 59

[tempfile,msg] = fopen('temperature.txt','r'); if tempfile < 0 disp(msg); else numTemps = fscanf(tempfile, '%d',1); % EOF determined by the count for i = 1 : numTemps temp(i) = fscanf(tempfile, '%f', 1); end
fprintf('Maximum value: %.1f \n', maximum(temp,numTemps)); fclose(tempfile); end
This program reads values from a data file and determines the maximum value with a function.
Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 23 of 59

[tempfile,msg] = fopen('temperature.txt','r'); if tempfile < 0 disp(msg); else % NO blank line at end of values numTemps = 0; while ~feof(tempfile) % Looks for EOF numTemps = numTemps + 1; temp(numTemps) = fscanf(tempfile, '%f', 1); end
fprintf('Maximum value: %.1f \n', maximum(temp,numTemps)); fclose(tempfile); end
This program reads values from a data file and determines the maximum value with a function.
Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 24 of 59

% This function returns the maximum % value in the array x with n elements. function max_x = maximum( x, n ) max_x = x(1); for k = 1:n if x(k) > max_x max_x = x(k); end end end

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 25 of 59

Arrays: Passing An Entire Array To Functions


maxTemp = maximum( temp,numTemps )

function max_x = maximum( x, n)

fprintf('Max temp: %.1f \n', maximum(temp,numTemps));


Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 26 of 59

Reading all values using load()


The load command reads values Saved with the save command Saved in text (.txt) All at once and assigns to the given variable name

clc, clear all temp = load('temperature.txt'); fprintf('Maximum value: %.1f \n', maximum(temp, numel(temp)));

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 27 of 59

To be continued

Auburn University Computer Science and Software Engineering

COMP 1200Matlab Course Notes Set 5 - 28 of 59

Вам также может понравиться