Solutions To Homework 6o
Solutions To Homework 6o
Help Center
Problem neighbor
function w = neighbor(v)
w = [];
if min(size(v)) == 1
% must be a vector
for ii = 1:length(v)-1
thing
w(ii) = abs(v(ii+1) - v(ii));
end
end
end
w = [];
else
w = abs(v(1:end-1)-v(2:end));
end
end
Problem replace_me
builds up the output one element at a time
function w = replace_me(v,a,b,c)
if nargin < 3
b = 0;
end
if nargin < 4
c = b;
end
w = [];
for k = 1:length(v);
if v(k) == a
% if a is found,
w = [w,b,c];
else
w = [w,v(k)];
end
end
end
wi = 1;
for vi = 1:length(v)
if v(vi) == a
w = [w(1:wi-1) b c w(wi+1:end)];
wi = wi + 1;
% increment wi
end
wi = wi + 1;
end
end
Problem halfsum
using nested loops
function s = halfsum(A)
[row col] = size(A);
s = 0;
for ii = 1:row
for jj = ii:col
s = s + A(ii,jj);
end
end
end
s = s + sum(A(r,r:end));
lusive)
end
end
Problem large_elements
function found = large_element(A)
[row col] = size(A);
found = [];
for ii = 1:row
for jj = 1:col
if A(ii,jj) > ii + jj
dexes
found = [found; ii jj]; % add a new row to the output matrix
end
end
end
end
problem one_per_n
using while-loop
function n = one_per_n(x)
n = 0;
sum = 0;
while sum < x && n <= 10000
n = n + 1;
sum = sum + 1/n;
end
if n > 10000
n = -1;
end
end
function n = one_per_n(x)
s = 0;
for n = 1:1e4
s = s + 1/n;
if s >= x
return;
end
end
n = -1;
end
Problem approximate_pi
function [a,k] = approximate_pi(delta)
k = 0;
f = sqrt(12);
a = f;
k = k + 1;
% increment k
a = a + f*(-3)^(-k)/(2*k+1);
end
end
Problem separate_by_two
using division and rounding
function [even,odd] = separate_by_two(A)
even = A(fix(A/2) == A/2)';
odd
= A(fix(A/2) ~= A/2)';
be equal
end
% note that this will put non-integers into odd
odd
= A(mod(A,2) == 1)';
end
% note that this one will not put non-integers in any of the outputs
ed to negate it
odd
= A(mod2)';
end
% note that this will put non-integers into odd
Problem divvy
function A = divvy (A,k)
L = (mod(A,k) ~= 0);
A(L) = k * A(L);
them by k
end
% uses A as both input and output, so we only need to modify some elements of A
Problem square_wave
using a for-loop
function sq = square_wave(n)
t = 0 : 4*pi/1000 : 4*pi;
sq = zeros(1,length(t));
% initialize output to 0
for ii = 1:2:2*n
sq = sq + cos(ii*t-pi/2)/ii;
end
end
Problem my_prime
using a for-loop
function a = myprime(n)
a = false;
if n > 1
for ii = 2:sqrt(n)
if ~mod(n,ii)
return;
end
end
a = true;
end
end
% x is prime if it is NOT divisible by all integers from 2 to sqrt(x)
% because factors have to come in pairs -- one bigger than sqrt(x) and
% one smaller (or both equal)
end
v = v(rem(p,v) == 0);