TASK: Use MATLAB's logical vectors and the find() command to analyze a vector.
COMMENT: In class, we walked about how, if x is a vector (or list), we can create a logical vector that records a 1 (TRUE) or 0 (FALSE) for each entry of x. So, if X = [ 1.2, -3.4, 0.5, -6.7, -8.9], then
i = ( x < 1 ) j = ( 0.0 < x && x < 5.0 )will result in
i = [ 0, 1, 1, 1, 1 ] j = [ 1, 0, 1, 0, 0 ]Sometimes, we want to count how many values of x satisfy a condition. For these examples, we could write
i_count = sum ( i ); j_count = sum ( j );which will report that 4 items in x are less than 1, and that 2 items are between 0 and 5.
The find() function can also be used for these kinds of questions. But instead of returning a 0 or 1, it returns a list of the indices in x for which the condition is true. Hence
i2 = find ( x < 1 ) j2 = find ( 0.0 < x && x < 5.0 )will result in
i2 = [ 2, 3, 4, 5 ] j2 = [ 1, 3 ]We can actually use the list of indices returned by find() to select just those elements of x.
x(i2) will print -3.4, 0.5, -6.7, -8.9and
x(j2) will print 1.2 0.5
Using logical vectors and find() commands, we can carry out some operations very simply, that would take much more work to express using "if/else" and "for" statements.
INSTRUCTIONS: write a function "hw044" that takes a vector x as input, and a value s, and returns
write the function header with the output, function name, and input. use ONE statement that defines "i", a logical vector that records whether elements of x are greater than s; use ONE statement to count s_num, the number of "TRUE' values in "i"; use ONE statement to define "j", the list of indices in X of entries that are greater than s; use ONE statement to compute s_sum, the sum of the entries in X that are greater than s.In other words, the "interesting" part of your function should consist of four statements, and NO "for" loops or "if/else" statements.
CHECK: x = [ 1.2, -3.4, 0.5, -6.7, -8.9 ]; s = -1.0; [ s_num, s_sum ] = hw044 ( x, s );
s_num will be 2. s_sum will be 1.7.
SUBMIT: Your script file should be named "hw044.m", and begin with:
% hw044.m % YOUR NAME % This script (describe what it does)