Q:

MATLAB Piecewise Functions + Vector Manipulation

I would like to write a program which plots the points on top of a semicircle on a certain interval and a straight line everywhere else. Something like this: __n__.
I defined a time domain, which was stored as a vector (t = 0:0.01:5). I assumed that I could define the points on the top of the semicircle using elements of the time vector:
if t>=2|t<=2.3
y = sqrt(.15^2-(t-2.15)^2);

but MATLAB produced an error message saying only square matrices can be squared.
I tried to utilize indices to show that I wanted to square an element of the t vector and not the whole vector:
i = [200:230];
for t(200:230)
y = sqrt(.15^2-(t(i)-2.15)^2);

After these failures, I noticed that squaring a square matrix with one column of non-zero elements would produce a new square matrix with a column of the first matrix's elements squared. If there is some way to eliminate the extra columns of zeros after squaring the matrix, I could use that property of matrices to square the values of the t vector.
What is the simplest and most effective way to address this problem?

A:

It sounds like you want to draw a horizontal line with a semicircular "bump" on it. Here's how you can do this:
t = 0:0.01:5;        % Create the time vector
y = zeros(size(t));  % Create a zero vector the same size as t
index = find((t >= 2) & (t <= 2.3));        % Find a set of indices into t
y(index) = sqrt(.15^2-(t(index)-2.15).^2);  % Add the "bump" to y
y(1:index(1)) = y(index(1));                % Add the line before the "bump"
y(index(end):end) = y(index(end));          % Add the line after the "bump"

In the above solution, the lines before and after the "bump" could be slightly higher or lower than one another (depending on where your samples in t fall). If you want to make sure they are at the same height, you can instead do the following:
index = (t >= 2) & (t <= 2.3);              % Find a set of logical indices
y(index) = sqrt(.15^2-(t(index)-2.15).^2);  % Add the "bump" to y
% OPTION #1:
y(~index) = y(find(index,1,'first'));  % Use the first circle point as the height
% OPTION #2:
y(~index) = y(find(index,1,'last'));   % Use the last circle point as the height

Finally, you can plot the line:
plot(t,y);

