1 / 44

Exam3 Coding Review

Exam3 Coding Review. Files xlsread () dlmread () fopen (), fclose () fgets (), fgetl () fscanf () textscan (). Arrays Slicing Diminution Finding data Filtering Analyzing data. Plotting. Functions Function file Using a function. I. Files.

bruno
Download Presentation

Exam3 Coding Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exam3Coding Review Files xlsread() dlmread() fopen(), fclose() fgets(), fgetl() fscanf() textscan() Arrays Slicing Diminution Finding data Filtering Analyzing data Plotting Functions Function file Using a function

  2. I. Files • Step1: OPEN and STUDY the file (2 minutes…) • Step2: Decide if high-level functions will do the trick • Step3: develop algorithm • Step4: code • Step5: test and check for errors! • omit semicolons and see what went wrong.

  3. A. Excel spreadsheets From the “less-work” to the “more-work”… • Assume it is an excel sheet. Use the function _____________ • This function returns 3 values, in order: [numbers, textdata, raw] = xlsread(‘file.xlsx’); • COLLECT UP TO the ones that are useful! this means: • numbers = xlsread(‘file.xlsx’); • [num, txt] = xlsread(‘file.xlsx’); • [num, txt, raw] = xlsread(‘file.xlsx’); • [~, txt] = xlsread(‘file.xlsx’); • …

  4. B. not excel sheets It is NOT an excel sheet, but it IS a file that can be opened by MATLAB easily (.txt, .csv, .dat, etc… NOT .docx..) • Assume it is a text filewith a constant amount of columns, numbers ONLY, and separated by a unique delimiter ( space, tabs, : , any symbol on the keyboard..) Not a single string within these files!! Which function?

  5. B. dlmread() • The function has: • 1 to 4 arguments possible • 1 return value: a numerical array Task: • Create 1 script file that uploads all of the previous file’s data.

  6. C. low-level So.. your file isn’t an excel sheet and it has text… >> high-level is no longer possible Note: you can still see a pattern

  7. C. low-level • Even if the pattern is on multiple lines! • (Even without pattern, it’s feasible. We’ll just code 1 line of code per 1 line of file… )

  8. C. low-level • Use low-level functions: • 3 steps minimum are required: 1) open the file. Indicate whether MATLAB should read, write or append to the file. 2) read data from the file orwrite data to the file 3) close the file

  9. C. Low-Level Functions • Open a file. Various options: fid = fopen(filename);%read is the default fid = fopen(filename, ‘r’); %to read fid = fopen(filename, ‘w’); %to write fid = fopen(filename, ‘a’); %to append

  10. C. Low-Level Functions “Number of columns in file”, or “Number of placeholders in format string” • Functions to read/write the data • Some are good with entire lines of “whatever” str = fgets(fid); str = fgetl(fid); • Some are good with numbers numerical_array = fscanf(fid, ‘format string’, [____, inf])’; cell_array= textscan(fid, ‘format string’); • Some are good with strings& numbers cell_array= textscan(fid, ‘format string’); • Note: the actual name of the file is N-E-V-E-R used in these function calls.

  11. C. Low-Level Functions • Close the file fclose(fid); %return-value can help check if file was closed, or simply ignored

  12. Examplesssss clc clear %open file to read %first line is titles %scan high scores of people %close file

  13. Examplesssss clc clear %open file to read %first line is titles %scan log and time in %close file

  14. Examplesssss clc clear %open file to read %skip first 3 lines %scan all data %close file CAUTION: The format string must look at ALL columns, even though we may only need columns 2, 5, and 17.

  15. How about “Write to a file”? • Suppose you want to create a .dat file with 20 lines, 3 columns? 1st column is a sequential number: 1,2,3,4… 2nd column is a random whole number between 1 and 5 3rd column is a random ID between 10000 and 20000.

  16. How about “Write to a file”? • Had it been to the screen…. clc clear forlineNb = 1:20 %run 20 times %random number between 1 and 5 col2 = ceil(rand*4); Id = round(rand*10000+10000); %random ID %print this line fprintf(‘%2d %5d %7d\n’, lineNb,col2,Id); end • To print the data to the file, very little has to be done!

  17. How about “Write to a file”? clc clear %OPEN FILE TO WRITE ______________________________ forlineNb = 1:20 %run 20 times %random number between 1 and 5 col2 = ceil(rand*4); Id = round(rand*10000+10000); %random ID %print this line TO THE FILE fprintf(______, ‘%2d %5d %7d\n’, lineNb,col2,Id); end %CLOSE THE FILE __________________________________ 1) open file, 2) write to file, 3) close file

  18. How about “Write to a file”? clc clear %open file in write mode! fid = fopen('data file.dat','w'); forlineNb = 1:20 %run 20 times %random number between 1 and 5 col2 = ceil(rand*4); Id = round(rand*10000+10000); %random ID %print this line to the file (NO MORE ON THE SCREEN) fprintf(fid, ‘%2d %5d %7d\n’, lineNb,col2,Id); end %close the file fclose(fid);

  19. How about “Write to a file”? clc clear %open file in write mode! fid = fopen('data file.dat','w'); forlineNb = 1:20 %run 20 times %random number between 1 and 5 col2 = ceil(rand*4); Id = round(rand*10000+10000); %random ID %print this line to the file (NO MORE ON THE SCREEN) fprintf(fid, ‘%2d %5d %7d\r\n’, lineNb,col2,Id); end %close the file fclose(fid); additional escape key

  20. Which functions? (end) • There really aren’t that many (taught…) • xlsread() • xlswrite() • dlmread() • fopen() • fgets() • fgetl() • fscanf() • textscan() • fprintf() • fclose() • FYI: MATLAB has many many more… There is a small (very small) debate between using 7 or 8. ALL OTHER are a no-brainer (if you learn the rules).

  21. II. So now you have arrays… • What to do with arrays????? • slice data • delete data • count and analyze data • plot data • There is sometimes a syntax difference between referencing numerical arrays () and cell-arrays ()/{}. However, the logic is always the same. Reference the cells/content you want, and apply the operation you want.

  22. A. Slicing numerical arrays • Slice a specific column array(:, 2) %all rows of column 2 • Slice a specific row array(5, : ) %5th row, all columns • Slice the top and bottom row only array([1 end], :) • Slice the 1st, 5th, and bottom row only array([1, 5, end], :) • Slice all the values above 0.5 array(array>0.5) %no need to know the exact positions!!  • Slice all the values between 10 and 15 array(10<array & array<15)

  23. A. Slicing cell-arrays (1) • LOOK AT HOW THE CELL ARRAY IS SET UP! (check the workspace) • SAME INFORMATION, but huge difference between these: cellArr2 1 by 3 cells cellArr1 3 by 3 cells When the array is small enough, use cellplot() to “plot” the pictures above!

  24. A. Slicing cell-arrays (2) • Slice all the names names1 = cellArr1(:,1); names2 = cellArr2{1}; • Similar operations are possible on the other columns

  25. A. What to do with that slice? • make a copy of it in a new variable x = array(:,1) %copy first column • delete it (if feasible) array(:,1) = [] • replace the values by others ones (if same dimensions) array(:,1) = 7 %replace all by scalars array(:,1) = [ 3, 4, 5, -6] %assuming 4 R-O-W-S • Count how many elements are in the slice? count = numel(array(array>0.5)) count = sum(array>0.5) • plot? bar?

  26. Examplessss • How many employees clocked in strictly before 8 AM? • How many employees clocked in strictly before 7:30 AM?

  27. Examplessss File is somewhat updated, and has the employee ID. • Which employees clocked in strictly before 8 AM? still unique delimiter.. so we can manage..

  28. B. Calculate data +- Arrays can be added/subtracted when the dimensions are identical * Arrays can be multiplied (A*B) only if the “inner” dimensions match. This means the number of columns of A equals the number of columns of B. / Array can be divided (A/B) only if B is a square matrix, with the same amount of rows/cols as A has columns. Note: There is ALWAYS an exception to the rule: scalars!

  29. B. Calculate data • If the array (matrix and vectors) have nothing to do with mathematics, then you may have to use the element-per-element operators: .* ./ .^ (note: there is no such thing as .+ and .- ) • For example:

  30. C. graph data • Review of vocabulary “plotting Y vs. X” In the plot() function: • 1st argument: X • 2nd argument: Y plot(X,Y); • MATLAB will thus plot “Y vs. X” • 3rd argument controls: • color • line marker • line type (NEVER LEARN BY HEART THE SYMBOLS!!) this is “Y vs. X” this is Y this is X

  31. C. graph data • Combine multiple plots? plot(x,y1, x,y2, x3, y3); %auto-colors plot(x,y1,‘r--’, x,y2,‘gd’, x3, y3); %override %the defaults or plot(x,y1); %blue hold on; plot(x,y2);%blue (no need to hold on anymore). %that’s done. plot(x3,y3,‘rs’); %red squares

  32. C. graph data • Don’t forget all the engineering “stuff”… title(‘my title goes here’); xlabel(‘labeling the x axis – (units)’); ylabel(‘labeling the y axis – (units)’); zlabel(‘labeling the z axis – (units)’); legend(‘string1’, ‘string2’, ‘string3’); • 99.99% of the time, we ignore return values!

  33. C. graph data • Other functions • plot3(x,y,z,‘rs’) • bar() requires one array of values as an argument code next slide..

  34. C. graph data • Test it at home!

  35. C. graph data • MATLAB does a lot of analysis for us in this one: • pie()

  36. C. graph data • MATLAB calculated the percentages!!  • note: very little changes from the bar() script file!

  37. III. All these could of course be functions • Functions receive arguments. • Arguments replace the parameters within the function file. • MATLAB executes code, millions of calculations if necessary, and returns values to the call. • the call COLLECTS the data and continues with the rest of the code.

  38. Example1. Function definition parameter return-info

  39. Example1. Function call • Calling from the command window (quick test) • Calling from a main code (easy to run again) (see next slide) arguments COLLECTING return-info

  40. Example1. Function call arguments COLLECTING return-info

  41. Example2. Function definition NO return-info  2 parameters

  42. Example2. Functions call(s) • Calling from the command window (quick test) • Calling from a main code (easy to run again) arguments NOTHING to collect!

  43. Wrapping Up • Files I/O • high-level • low-level • Arrays • slicing • mathematics • Graphing • plot() • bar() • pie() • Programmer-defined functions • 2 examples of definitions AND calls

  44. Good luck on Exam3

More Related