%------------------------------------------------------------------------------ % CS100J, Spring 2000 % Lecture 25 % Tues 4/24 %------------------------------------------------------------------------------ % Notation: clc more on echo on % + menus: "->" means selecting a submenu % example) File->Set Path means "click on File menu then click on Set Path % submenu" % + CW means "Command Window" % + MF means "M-File" %------------------------------------------------------------------------------ % Handy commands for programming % pause % I am assuming you're trying to run this MATLAB % $pause$ pauses processing of the MF until you hit any key % no, there's no "Any" key :-) % echo % repeat everything in the MF that was run % the CW still evaluates everything in the MF % more neat stuff: % + miscellaneous: see $keyboard$, $pause(n)$, $waitforbuttontopress$ % + input: $input$ % + output: $disp$ %------------------------------------------------------------------------------ % Example1 % -------- % World's most common intro program % Print Hello, World! to user disp(['Hello, World!']) % display output pause % pause for keystroke % explanation: $disp$: display an array of strings % - 'Hello, World!' is a string % - ['Hello, World!'] is an array containing one string % - disp(['Hello, World!']) tells MATLAB to display % 'Hello, World!' in the Command Window %------------------------------------------------------------------------------ % Example2 % -------- % Let's clean that up a bit for the MATLAB interface. % "cleaning up" here means making the program a bit more user-friendly. % Example 1 is called "bare-bones" because little is explained to the user. % Print Hello, World! to user clc % clear screen disp(['Running a classic program....']) disp(['Hello, World!']) disp(['Hit any key when ready to continue']) pause %------------------------------------------------------------------------------ % Example3 % -------- % Now let's be a bit fancier. % Calculator-type program % Ex2 determines the percent error for a measured quantity % compared to an ideal value. % Determine percent error clc disp(['Hello, user. I am about to calculate a percent error.']) % Get measured and ideal values measured = 11; % a measured value ideal = 10; % an ideal, or perfect) value % Formula to determine percent error % For absolute value, use ABS function: abs(value) percenterror = 100*abs(measured-ideal)/ideal; % Output to user disp(['The percent error is ' num2str(percenterror)]) disp(['Hit any key when ready to continue']) pause % notes % ----- % + MATLAB processes each statement one at a time % (technically, MATLAB interprets each statement) % + the code works left to right, top to bottom % (known as control-flow or flow of control -> the fact that % the software executes in a controlled fashion) % + $num2str$ converts the numerical value of $percenterror$ to % a string. $disp$ displays an ARRAY of strings, so I left a space % between the first and second strings %------------------------------------------------------------------------------ % Example4 % -------- % The last program involved a black box and output. % It would be more fancy (and useful) if the user could choose the values % used in evaluating percent error. % Use $input$ command...demonstrated below, then explained more in Ex5 % Determine percent error clc disp(['Hello, user. I am about to calculate a percent error.']) % Obtain input from user measured = input('Enter a measured value: '); ideal = input('Enter the ideal value: '); % Formula to determine percent error % For absolute value, use ABS function: abs(value) percenterror = 100*abs(measured-ideal)/ideal; % Output to user disp(['The percent error is ' num2str(percenterror)]) disp(['Hit any key when ready to continue']) pause % notes % ----- % How does $input$ work? % $input(string)$ causes MATLAB to prompt the user for input % + a prompt is text output that tells the user what to do % + the $input$ command outputs the string as the prompt % MATLAB then waits for the user to input a value or array % (an array would be entered with brackets []) % That input value is then stored in the variable on the left side. % Try picturing that the input value from the user replaces the entire % code on the right side of the assignment. %------------------------------------------------------------------------------ % Example5 % -------- % More practice using $input$ clc disp(['Now demonstrating more about input....']) echo % test1) input('Enter it! ') % In test1 MATLAB waits for the user input. % The user types a value and presses Enter. % MATLAB replaces "input('Enter it! ')" with the value you entered. % So, MATLAB reports "ans = " % Notice how I put a space in the string because the input appears % immediately to the right of the string. pause clc 'Next test...'; % test2) L = input('R: ') L % In test2 I'm using variables L and R to remind you about what's on % the left and right, respectively. I enter L AGAIN so MATLAB can prove % to you that L is assigned pause clc 'Last test...'; % test3) L = input('R: '); % In test3, do you see the semicolon? Why on Earth did I do that? % MATLAB evaluates the right-side as your input value. % Any time you enter a value, what does MATLAB do? Evaluates it. % So, the semicolon suppresses the output of assigning the input to % the variable on the left. echo pause %------------------------------------------------------------------------------ clc % Conditional Statements % + also known as selection statements % + so far, programs seen as top-down sequence of instructions % + often problems require choices % + need to express situations as TRUE and FALSE % + use tests to cause branches in the program pause %------------------------------------------------------------------------------ clc % Logic % + use to test situations % + tests called RELATIONS % value op value % + MATLAB evaluates the statement for truth % + answer is either 1 (true) or 0 (false) % examples) 1 < 2 % less than 1 == 1 % equal (true) 1 == 2 % equal (false) % source of confusion: % $==$ is a comparison for equality % $=$ is an assignment operator pause % logical operators: & (and), | (or), ~ (not), xor (exclusive or) 1==1 & 2==2 1 > 2 | 1 < 2 xor(1 < 2,1 < 3) pause %------------------------------------------------------------------------------ clc % Branches % + making choices % + use $if$ (skip $switch$) % + see $help if$ % General form of the $if$ statement is % % IF expression % statements % ELSEIF expression % statements % ELSE % statements % END % % + Must have $if$ and $end$ % + $else$ and $elseif$s are optional pause %------------------------------------------------------------------------------ clc % Example 1 % Test if a number is positive x = input('Enter a number: '); if x > 0 disp(['Your number is positive.']) end pause %------------------------------------------------------------------------------ clc % Example 2 % Test if a number is positive x = input('Enter a number: '); if x > 0 disp(['Your number is positive.']) else disp(['Your number isn't positive.']) end pause %------------------------------------------------------------------------------ clc % Example 3 % Test sign of a number (see $help sign$ for built-in function) x = input('Enter a number: '); if x > 0 disp(['Your number is positive.']) elseif x < 0 disp(['Your number is negative.']) else disp(['Your number is zero.']) % but can you guarantee that??? end pause %------------------------------------------------------------------------------ clc % Example 4 % Test sign of a number (see $help sign$ for built-in function) x = input('Enter a number: '); if x > 0 disp(['Your number is positive.']) elseif x < 0 disp(['Your number is negative.']) elseif abs(x) < eps disp(['Your number is zero.']) % but can you guarantee that??? else disp(['I don't know what the hell your number is.']) end pause %------------------------------------------------------------------------------ clc % Example 5 % Test sign of a number test = input('Enter the number to test: '); if isnumeric(test) if x > 0 disp(['Your number is positive.']) elseif x < 0 disp(['Your number is negative.']) elseif abs(x) < eps disp(['Your number is zero.']) else disp(['I don't know what the hell your number is.']) end else disp(['I said "Enter a number." Now look what you have done!']) end pause %------------------------------------------------------------------------------ % more about selection statements % % example) swap values disp(['swapping values']) v1 = input('give me value1: '); v2 = input('give me value2: '); % swapping using a "temporary" variable % $tmp$ acts as a placeholder tmp = v1; v1 = v2; v2 = tmp; disp(['v1 now has v2 value: ' num2str(v1)]) disp(['v2 now has v1 value: ' num2str(v2)]) disp(['press any key to continue']) pause clc % now, apply to problem: % Find the maximum of stored value and input value % Keep the smaller value in variable called $min$ % input disp(['finding a max value']) max = input('give me a value: '); val = input('give me another value: '); % testing and swapping if (val > max) min = max; max = val; else min = val; end % output min max % curiosity val % what happens to $v1$? nothing clear val % if you want to erase $v1$ % val % now unassigned! %------------------------------------------------------------------------------ % Loops %------------------------------------------------------------------------------ % WHILE loop % From $help while$ % % WHILE Repeat statements an indefinite number of times. % The general form of a WHILE statement is: % % WHILE expression % statements % END % % The statements are executed while the real part of the expression % has all non-zero elements. The expression is usually the result of % expr rop expr where rop is ==, <, >, <=, >=, or ~=. % % The BREAK statement can be used to terminate the loop prematurely. %------------------------------------------------------------------------------ pause clc % example) count numbers from 1 to n x = 0; % x "so far" stop = input('enter stopping value n: '); % note: % variables that generalize a program $stop$ are called % NAMED CONSTANTS -- use them in as many palces as you can % output column of values from 1 to $stop$ while (x < stop) x = x + 1 % increment x by 1 pause end x % what's x when loop ends? %------------------------------------------------------------------------------ % example) count numbers from 1 to n % this time, store the numbers in an array x = 0; % x "so far" stop = input('enter stopping value n: '); % note: % variables that generalize a program $stop$ are called % NAMED CONSTANTS -- use them in as many palces as you can % output column of values from 1 to $stop$ if stop>=0 y = zeros(1:stop-x) % what if x isn't zero? else disp(['evil x!']) break % actually, you should avoid $break$s at all cost... % For a taste of Java, think "System.exit(0)" end i = 1 % index for vector y while (x < stop) x = x + 1; % increment x by 1 y(i) = x i = i + 1; pause end x % what's x when loop ends? y % notes: % ----- % boundary conditions -- I have loop possibly stopping for a count of % zero. That's a kind of boundary condition, or limiting value % Actually, the result isn't too pretty if you enter 0 for $stop$. % MATLAB returns the empty matrix $[]$ % % vectorizing -- overall my style is OK here, but there's some efficiency % problems. You don't really need a loop to gather a count of values! % Vectorizing code means finding a way for MATLAB's array to % supercede a loop. Using built-in arrays generally works faster than % processing a loop. Not all languages have this feature, though. % % other commands: $tic$, $toc$, $break$, $for$ %---------------------------------------------------------------------------- % FOR LOOP % see $help for$: % % FOR Repeat statements a specific number of times. % The general form of a FOR statement is: % % FOR variable = expr, statement, ..., statement END % example) print list of numbers from 1 to 4, stepping by 1: pause clc for ii=1:4 x end % example) print list of numbers from 1 to 4, stepping by 0.5: pause clc for ii=1:0.5:4 x end %---------------------------------------------------------------------------- % So, what's the colon about? See $help colon$ and next lecture on arrays. %---------------------------------------------------------------------------- % some more examples: % % repetition (well, a bit of updating) % set up input i=1 g = input('enter grade: ') % perform repetitive task until % user enters a negative value while g > -eps grades(i) = g i = i+1 g = input('enter grade: ') end if i > 0 grades else disp(['no grades entered!']) end % conditional update % set up input i=1 g = input('enter grade: ') max = g % max value "so far" % find max from input grades while g > -eps grades(i) = g i = i+1 g = input('enter grade: ') if g > max max = g end end if i > 0 max grades else disp(['no grades entered!']) end