%% Question 2a

% The code is determining if each element of vec is less than 0.

result = vec < 0;


%% Question 2b

% The code is computing the average value of all of the elements in A

result = mean(A(:));


%% Question 2c

% There are many possible solutions, but they all start with:
n = length(v);
D = zeros(n, n);

% Using nested loops:
for r = 1:n
    for c = 1:n
        if r == c
            D(r, c) = v(r);
        end
    end
end


% Using a single loop:
for i = 1:n
    D(i, i) = v(i);
end




%% Question 3a

[X, Y] = textread('baddata.txt', '%f %f', 'headerlines', 1);

%% Question 3b
hist(X, 20);
hold on
hist(Y, 20);

% The correct X measurements are all greater than 30
% The correct Y measurements are all less than 130


%% Question 3c

% Using a loop:
n = length(X);
for i = 1:n
    x = X(i);
    y = Y(i);
    if x < 30
        X(i) = NaN;
        Y(i) = NaN;
    end
end

% Without a loop:
I = find(X < 30);
X(I) = NaN;
Y(I) = NaN;

%% Question 3d

boxplot([X Y], {'X', 'Y'});


%% Question 3e

X(isnan(X)) = [];
Y(isnan(Y)) = [];

mean(X)
std(X)

mean(Y)
std(Y)


%% Question 4a

x >= 0 & x <= 10


%% Question 4b

% Use a for loop if you know how many times the loop should iterate,
% and use a while loop otherwise.


%% Question 4c

% The closeness of the median to the true value is related to the
% accuracy.
% The length of the box and whiskers is related to the precision
% (shorter box and whiskers means greater precision).


%% Question 4d

% The function is very slow because s has not been pre-allocated.
% A simple solution is to pre-allocate s and assign directly to s(idx):

s = x;
for idx = 2:length(x)
    sprev = s(idx - 1);
    s(idx) = sprev + x(idx);
end



