Download presentation
Presentation is loading. Please wait.
1
General Computer Science for Engineers CISC 106 Lecture 09 James Atlas Computer and Information Sciences 9/25/2009
2
Objectives Use For Loops to Solve Problems nested loops Use While Loops Plot Functions
3
For Loops Used when you know how many times code is to be executed. Syntax for = [ : : ] Variable is initially the start value At end of iteration variable changes by increment If value is not greater than end the loop runs again. is optional, if not provided will be 1
4
Sum a vector with a for loop
5
Sum a matrix with a for loop How do we know how many elements are in the matrix? >> b = [1 2 3; 4 5 6] >> length(b) ans = 3 >> size(b) ans = 2 3
6
Sum a matrix with a nested loop
7
A Loop Analogy (for) The runner executes a loop. If they know the distance they want to run For loop for lapCount = start : 1 : end runLap() end
8
A Loop Analogy (while) The runner executes a loop. If they don’t know the distance they want to run (run until tired) While loop tired = false; while(~tired) tired = runLap() end
9
While loop while expression statement end
10
While loop for sum vector
11
Plot Using the plot command plot(, ) where array1 is the x-axis and array2 is the y-axis NOTE: array1 and array2 must be equal in terms of size of dimensions!
12
Plot For example: x=[1 2 3 4 5]; y=[10 20 30 40 50]; plot(x,y)
13
Plot Other useful command with plot xlabel(‘ ’) – sets the label for the x-axis ylabel(‘ ’) – sets the label for the y-axis grid on – creates a grid title(‘ ’) – sets title of the plot
14
Plot For example: x=0:1:10; y=x.^2 - 10.*x + 15; plot(x,y)
15
Plot commands title(‘Graph Title’); xlabel(‘X axis label’); ylabel(‘Y axis label’); grid on; legend(‘series 1’, ‘series 2’,..., ‘BR’); print -dpng mygraph.png
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.