Presentation is loading. Please wait.

Presentation is loading. Please wait.

Storing two-dimensional numerical data

Similar presentations


Presentation on theme: "Storing two-dimensional numerical data"— Presentation transcript:

1 Storing two-dimensional numerical data
Matrices Storing two-dimensional numerical data - next couple lectures: learn about matrices, one of core structures in MATLAB (name from “Matrix Laboratory”) - we’ll initially uses matrices as means for storing 2-D numerical data - what contexts you’ve seen matrices? HS algebra? solving linear equations? rotating coordinates? courses or applications?

2 Analyzing table data level 1998 1999 2000 2001 2002 2003 2004 2005 advanced 7 9 15 18 20 24 29 35 proficient 17 27 28 needs improvement 23 22 30 31 failing 52 53 45 25 - table shows statewide results of MCAS Test in Math for Grade 10 students, over years , indicating percentage of students who achieved each level of performance - MCAS stands for Massachusetts Comprehensive Assessment System and evaluates public education in state. Grade 10 students need to pass this exam in order to graduate HS Statewide results for MCAS Test in Mathematics, Grade 10 Matrices

3 Medical imaging Matrices are particularly good for storing data that is inherently two-dimensional For example, the illustrated MRI slice is obtained from a two-dimensional grid of brightness measurements registered by an array of light sensitive elements - matrices also good for storing data that is inherently 2-D, one example is images, such as this MRI image - we’ll begin with basic background on matrices in MATLAB, then consider a couple examples involving processing images, then more basics - later in semester, you’ll build a tool for visualizing MRI data in different ways Matrices

4 Matrices: The basics A matrix is a rectangular array of numbers
We create a matrix of specific values with an assignment statement: >> flowers = [ ; ; ] flowers = 1 3 2 7 6 4 5 8 - tired of “nums” and “numbers” – with all new snow, time to think spring, flowers - suppose we have explicit values want to store in matrix - list inside brackets as we did with vector - each row of values is separated by a semi-colon (note no semi-colon after last row) - contents of each row can be written with or without commas between values - we’ll write them without - MATLAB prints values row-by-row without brackets - visualize as 2-D grid of numbers (1st, 2nd, 3rd rows) flowers Matrices

5 Dimensions Each row must contain the same number of values!
nums = [ ; 6 8] size function returns the number of rows and columns in a matrix: >> dims = size(flowers) dims = 3 4 >> rows = size(flowers, 1) rows = 3 >> cols = size(flowers, 2) cols = 4 1 3 2 7 6 4 5 8 flowers - when creating matrix of explicit values, each row must have same number of values - if not, error: dimensions not consistent - used length function to determine number of elements in vector, we use “size” with matrices - in first case, row and columns returned by size are stored in a vector: [rows cols] - how refer to each dimension? dims(1) or dims(2) - another way to call size function: add second input that specifies which dimension you want - numEntries = prod(dims) prod(size(flowers)) rows*cols How could you determine the total number of elements in a matrix? Matrices

6 Déjà vu all over again Many computations can be performed on an entire matrix all at once flowers = 2 * flowers + 1 1 3 2 7 6 4 5 8 flowers 3 7 5 15 13 9 - just like vectors… - arithmetic operations that combine matrix and numbers - same operations applied to every element of matrix, producing matrix of results - final rows 2 and 3: flowers Matrices

7 Element-by-element matrix addition
sumFlowers = flowers + addOns 3 7 5 15 13 9 11 17 2 1 3 4 + flowers addOns 5 8 19 15 13 = - also just like vectors, can perform arithmetic operations between two matrices, element-by-element - with old friend .* - use ./ for element-by-element division and .^ to raise each element to power, e.g. >> squares = flowers.^2 - what do you think * does? matrix multiplication error here: (3 x 4) * (3 x 4) (inner dimensions error) - important: to perform element-by-element operations on two matrices, the matrices must be the same size, i.e., same number rows and same number columns sumFlowers How do you perform element-by-element multiplication? Matrices

8 Vectors are matrices… … with one row or column
rowNums 1 2 3 rowNums = [ ] rowNumsSize = size(rowNums) colNums = [1; 2; 3] colNumsSize = size(colNums) length function returns the largest dimension rowNumsSize 1 3 1 colNums 2 3 - just learned that similar operations can be performed on matrices and vectors – not surprizing – vectors are just matrices with one row or col - we distinguish with names vector/matrix, but to MATLAB, all same - create colNums with semi-colon after each number, stored in column vector with dimensions 3 x 1 >> num = 2; >> size(num) ans = - for vector, value returned by length would correspond to the number of elements in the vector - we need to be more cautious about some of the functions that we may want to use with matrices colNumsSize 3 1 Matrices

9 Now I know what you’re thinking…
You probably think that we can use functions like sum, prod, min, max and mean in the same way they were used with vectors: numbers = [ ; ] totalSum = sum(numbers) totalProd = prod(numbers) minVal = min(numbers) maxVal = max(numbers) meanVal = mean(numbers) 1 3 2 4 numbers 4 1 2 3 - these are valid statements in MATLAB, but don’t have quite the effect you’re probably thinking… Matrices

10 Hmmm… that’s not what I expected…
numbers = [ ; ] totalSum = sum(numbers) totalProd = prod(numbers) minVal = min(numbers) maxVal = max(numbers) meanVal = mean(numbers) 1 3 2 4 numbers 4 1 2 3 totalSum 5 4 4 7 totalProd 4 3 4 12 - performs operations within columns, giving vector of results for each column - compute sum of all the numbers in matrix: sum(sum(numbers)) - how can you modify this statement to compute the product, min, max and mean values of all the contents of a matrix? - awkward, but the way things are in MATLAB… - follow-up sum, prod, min, max, mean: sum(numbers, 1) sums across the rows of the matrix - equivalent to sum(numbers) sum(numbers, 2) sums across cols - [10; 10] column vector - prod and mean behave the same way (example) - min(numbers, [], 1) min(numbers, [], 2) - extra empty vector in middle, same with max - min(numbers, 2) returns matrix of same size as numbers whose entries are the minimum of the current entry and 2, similarly with max(numbers, 2) minVal 1 1 2 3 meanVal 2.5 2.0 2.0 3.5 maxVal 4 3 2 4 Matrices

11 Processing and displaying images
An image is a two-dimensional grid of measurements of brightness We will start with images with brightness ranging from black (0.0) to white (1.0) with shades of gray in between (0.0 < b < 1.0) - e.g. brightness measured with a digital camera - black & white, or “gray-level” images - represent images as 2-D matrix of numbers, 0.0 to 1.0 1887 Crew Team Wellesley College Matrices

12 Creating a tiny image >> imshow(tinyImage) tinyImage
; … ; … ] 0.0 0.0 0.0 0.0 0.0 0.0 >> imshow(tinyImage) 0.0 0.5 0.5 0.5 0.5 0.0 0.0 0.5 1.0 1.0 0.5 0.0 - images are typically very large, at least 128 elements on a side - very tiny image (6x6) with 3 levels of brightness - white (1.0) in center, surrounded by medium gray (0.5) and black (0.0) - function imshow displays image in figure window, see how looks in MATLAB - while there, pursue mystery… ( next slide) (use setupImages.m to create images for display) - display functions from MATLAB Image Processing Toolbox - imshow(tinyImage) (enlarge figure window by dragging corner) - imshow(image) (corrupted mystery image) tool bar: save, print, zoom in, zoom out, pan 128 x 128 image, each block is one element - imtool(image) allows you to see numbers, dragging doesn’t enlarge image - use menu, zoom in, zoom out, pan - individual locations: pixels (picture elements), lower left: x,y coords (matrix indices), brightness (1,1): upper left corner to (128,128) lower right - show pixel region tool tinyImage 0.0 0.5 1.0 1.0 05 0.0 (not to scale) 0.0 0.5 0.5 0.5 0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 Matrices

13 A mystery: Who stole The Beast?
This very corrupted image was received by anonymous courier late last night Let’s figure out what’s in it using the Image Processing Toolbox >> imtool(image) - what are all those bright specks (1.0)? Let’s get rid of them by changing brightness at those locations to brightness of background >> image(image == 1.0) = 0.45; (similar to vector) - something emerging, but dark, low contrast. Let’s beef up contrast - helps to know range of brightness values in image: >> minV = min(min(image))  >> maxV = max(max(image))  - now expand range of brightness by shifting darkest brightness value down to 0.0 and stretch out values so they span range 0-1 >> image = image -minV; check min/max again >> minV= min(min(image)  0 >> maxV = (max(max(image))  - but we want max to be 1, so multiply each value in image by 1/ or about 18 >> image = image * 18; >> imshow(image)  Sohie! (with measles…) Matrices

14 Creating matrices with constant values
To create a matrix of all ones: nums1 = ones(2,3) nums2 = ones(1,5) To create a matrix of all zeros: nums3 = zeros(3,1) nums4 = zeros(4,3) 1 1 1 nums1 1 1 1 nums2 1 1 1 1 1 - sometimes useful to create a matrix of particular size, initially filled with constant value (trust me!) - can use to create vectors as well, but still need to give two dimensions - suppose want to create initial matrix 2x4, filled with 10’s? >> tens = 10*ones(2,4) nums4 nums3 Matrices

15 Indexing with matrices
Each row and column in a matrix is specified by an index nums = [ ; ] We can use the indices to read or change the contents of a location val = nums(2,3) nums(1,4) = 9 nums(1,end) = 9 1 3 7 4 8 5 2 6 nums - first row, first column have index 1, indices increment by 1 for successive rows/cols - val = 2, the 4 in row 1 column 4 changes to 9 - keyword end, when provided as a row or column index for a matrix, refers to the last index of the row or column Similar to vectors Matrices

16 Time-out exercise Starting with a fresh copy of nums
what would the contents of nums and val be after executing the following statements? nums(2,3) = nums(1,2) + nums(2,4) nums(1,3) = nums(1,4) + nums(2,1) val = nums(4,3) 1 3 7 4 8 5 2 6 nums - 2 changes to 9 - 7 changes to 12 - last one is a trick, we are attempting to read the contents of a location whose index is outside range of indices of the matrix and an error is generated Matrices

17 Auto expansion of matrices
>> nums = [ ; ] >> nums(4, 7) = 3 1 3 7 4 8 5 2 6 nums nums 1 2 3 4 5 6 7 1 3 7 4 - ability to expand a vector automatically can be advantageous at times, but can also be a source of bugs in your code. Beware! - important note: when MATLAB automatically expands matrix, allocates new memory space to store the larger matrix and copies contents - this process takes time! This is one reason why we create initial matrices of appropriate size with the ones and zeros functions 1 2 8 5 2 6 3 4 3 Matrices

18 Analyzing table data level 1998 1999 2000 2001 2002 2003 2004 2005 advanced 7 9 15 18 20 24 29 35 proficient 17 27 28 needs improvement 23 22 30 31 failing 52 53 45 25 - table shows statewide results of MCAS Test in Math for Grade 10 students, over years , indicating percentage of students who achieved each level of performance - MCAS stands for Massachusetts Comprehensive Assessment System and evaluates public education in state. Grade 10 students need to pass this exam in order to graduate HS Statewide results for MCAS Test in Mathematics, Grade 10 Matrices

19 Indexing with colon notation
To refer to an entire column of a matrix, provide : as the first index and the column number as the second index >> nums(:, 3) ans = 3 8 13 18 To refer to an entire row of a matrix, provide : as the second index and the row number as the first index >> nums(2, :) nums 1 2 3 4 5 1 2 3 4 5 1 2 6 7 8 9 10 3 11 12 13 14 15 4 16 17 18 19 20 - suppose we have a table of information and want to select entire column or row of our data for analysis or for plotting (in a moment…) - suppose nums(:, end) or nums(end, :) Matrices

20 Plotting trends in performance levels
We begin our analysis by plotting the data for each performance level over the 8 years % create matrices that store data and years results = [ ; ... ; ... ; ... ]; years = [ ]; Each row of the table corresponds to a performance level. How do we plot the resulting trend over the given years? >> plot(years, results(1, :), ‘b’); (advanced) - since we’re drawing several plots on same graph, it would be good to “hold on” until we’re done - I like to draw thick lines, using LineWidth property plot(years, results(1,:), ‘b’, ‘LineWidth’, 2) Matrices

21 Plotting the data % plot the data for each performance level vs. years
hold on plot(years, results(1,:), 'b‘, ‘LineWidth’, 2); plot(years, results(2,:), 'g‘, ‘LineWidth’, 2); plot(years, results(3,:), 'c‘, ‘LineWidth’, 2); plot(years, results(4,:), 'r‘, ‘LineWidth’, 2); hold off xlabel('year‘) ylabel('percentage of students‘) title('MCAS results‘) legend('advanced‘, 'proficient‘, 'improve‘, 'failing‘ ); - plots with different colors, all thick, and usual labels, title, legend (strings in order plotted) Matrices

22 Finally, ... Suppose we want to print the change in results between 1998 and 2005 for each performance level… How do we do this? - can begin with creating column vector with changes for all four levels: totalChange = results(:, end) - results(:, 1) Matrices

23 Printing changes in results
% print total change in results between 1998 and 2005 totalChange = results(:, end) - results(:, 1); disp('Change in performance between 1998 and 2005:‘); disp(['advanced: ' num2str(totalChange(1)) '%‘]); disp(['proficient: ' num2str(totalChange(2)) '%‘]); disp(['needs improvement: ' num2str(totalChange(3)) '%‘]); disp(['failing: ' num2str(totalChange(4)) '%‘]); - recall general form of the disp function is disp([string1 string2 ... stringLast]); - concatenates all the strings (note spaces) - num2str converts number to string (if omitted, MATLAB prints a box for the number) Change in performance between 1998 and 2005: advanced: 28% proficient: 10% needs improvement: 0% failing: -37% Matrices

24 Time-out exercise For each year, compute a weighted sum of the four percentages, using a weight of 1 for “advanced”, 2 for “proficient”, 3 for “needs improvement” and 4 for “failing”* overallPerformance = Add a new row to the results matrix that stores these weighted sums overallPerformance = 1 * results(1,:) + 2 * results(2,:) … + 3 * results(2,:) + 4 * results(4,:) - hmmm, that looks vaguely familiar: [ ] * [ … ] - our old friend matrix multiplication does the trick: overallPerformance = (1:4) * results - let’s take advantage of auto-expansion of matrix: results(5,:) = overallPerformance * The resulting sum can range from 100 (great!) to 400 (not so good…) Matrices

25 More indexing with colon notation
We can use colon notation to refer to a range of indices within a column or row of a matrix >> nums(1:3, 4) ans = 4 9 14 >> nums(3, 3:5) >> nums(2:3, 2:4) nums 1 2 3 4 5 1 2 3 4 5 1 2 6 7 8 9 10 3 11 12 13 14 15 - suppose want to refer to subset of row or column, or rectangular region of values within matrix - nums(2:end, 3:end) - suppose use in assignment: nums(2:end, 3:end) = 10 4 16 17 18 19 20 Matrices

26 Conditional operations on matrices
A conditional expression can be applied to an entire matrix all at once producing a new matrix of the same size that contains logical values ages = [ ; ; ]; teens = (ages >= 13) & (ages <= 19); ages teens 13 52 19 21 1 1 - recall that we used this idea when interpreting the noisy image of Sohie: image(image == 1.0) = 0.45 18 47 23 15 1 1 60 38 16 12 1 Matrices

27 Using logical vectors >> ages(teens) = 0 ages = 0 52 0 21
>> overTheHill = ages(ages>40) overTheHill = 60 52 47 13 52 19 21 ages 18 47 23 15 60 38 16 12 1 1 teens - in the overTheHill example, answers are selected column-by-column, and all values are then collected into a single column vector 1 1 1 Matrices

28 Time-out exercise Given the original ages matrix, write two statements that each assign the variable numAdults to the total number of age values that are 18 or over One statement should use sum and the other should use length numAdults = sum(sum(ages >= 18)) numAdults = length(ages(ages>=18)) Matrices


Download ppt "Storing two-dimensional numerical data"

Similar presentations


Ads by Google