%------------------------------------------------------------- % % Randall Bramley % Department of Computer Science % Indiana University, Bloomington % bramley somewhere at cs dot indiana dot (allegedly) edu % % Started: Mon 04 Feb 2008, 09:05 AM % Last Modified: Mon 16 Feb 2009, 03:58 PM % %------------------------------------------------------------- more on; echo on; %--------------------------------------------------------------------- % % Example of using relational and logical operators to create arrays % that represent signals with discontinuities, or with other values % replacing a segment of the original signal. In Matlab, a "signal" % is an array, and some apps require complex numbers in the array. % % Main idea: Multiply the values in an array you want to keep by ones, % and multiply all the other values by zeros. Then you can replace % the zero-ed out entries with other values by adding into them % signals which themselves have zeros on the segments you want to keep. % % Confusing explanation? Good. Look at the actual values, maybe % after setting n to something smaller. % % A new ingredient here is the setdiff() function. See how it is % used below to see how it works. % % Another new thing (to you) is how to eliminate part(s) of a vector. % %--------------------------------------------------------------------- n = 100; x = linspace(1,10,n); y = sin(x); figure; plot(x, y, 'b+-'); title('Unmodified sine function'); xlabel('Radians'); ylabel('signal = f(x)'); z1 = (y >= 0).*y; % Gives array same as y, but with negatives values % set to zero. figure; plot(x, z1, 'g*-'); title('Sine with negative values replaced by zeros'); xlabel('Radians'); ylabel('signal = f(x)'); z2 = z1 + 0.5*(y < 0); % Where sin(x) is negative, add 1/2 figure; plot(x, z2, 'r*-'); title('Sine with negative values having 1/2 added'); xlabel('Radians'); ylabel('signal = f(x)'); z3 = (x <= 8) .* z2; % Set values past x = 8 to be zero figure; plot(x, z3, 'mo-'); title('Sine with values of x over 8 set to zero'); xlabel('Radians'); ylabel('signal = f(x)'); I = find(x <= 8); J = setdiff(1:n, I); z4 = (x <= 8) .* z2; z4(J) = NaN; figure; plot(x, z4, 'kp-'); title('Sine with values of x over 8 replaced with NaN'); xlabel('Radians'); ylabel('signal = f(x)'); echo off; disp('Compare figures 4 and 5 to see why NaN can be useful.'); disp('What if +/- infinity is used instead of NaN?') disp('-------------------------------------------------------'); disp('Next, compare using NaN and deleting the values.') disp('Spot the difference? What does it imply about NaNs and plots?'); z5 = (x <= 8) .* z2; z5(J) = []; x(J) = []; figure; plot(x, z5, 'mv-'); title('Sine with values of x over 8 deleted'); xlabel('Radians'); ylabel('signal = f(x)'); unstack more off;