This repository has been archived on 2021-03-28. You can view files and clone it, but cannot push or open issues or pull requests.
ICS/hw2/assignment2.m

91 lines
1.7 KiB
Matlab

%% Assignment 2
% Name: Claudio Maggioni
%
% Date: 19/3/2019
%
% This is a template file for the first assignment to get started with running
% and publishing code in Matlab. Each problem has its own section (delineated
% by |%%|) and can be run in isolation by clicking into the particular section
% and pressing |Ctrl| + |Enter| (evaluate current section).
%
% To generate a pdf for submission in your current directory, use the following
% three lines of code at the command window:
%
% >> options.format = 'pdf'; options.outputDir = pwd; publish('assignment2.m', options)
%
%% Problem 3
syms x;
f = exp(x);
df = diff(f);
x_0 = 1;
err = zeros(10, 1);
h = zeros(10, 1);
for i = 1:10
h(i) = 10^(-i);
err(i) = abs(subs(df,x,x_0) - my_diff(f, x, x_0, h(i)));
end
loglog(h, err)
%% Problem 6
n = 3000;
A = rand(n,n);
B = rand(n,n);
tic
[C] = matTimesMat_classical(A, B);
toc
norm(C - A * B) / norm(C)
tic
[C] = matTimesMat_column(A, B);
toc
norm(C - A * B) / norm(C)
tic
[C] = matTimesMat_outerProd(A, B);
toc
norm(C - A * B) / norm(C)
%% Problem 3 (functions)
function approx = my_diff(f, x, x_0, h)
approx = (subs(f,x,x_0 + h) - subs(f, x, x_0)) / h;
end
%% Problem 6 (functions)
function [C] = matTimesMat_classical(A, B)
s = size(A);
n = s(1);
C = zeros(n);
for i=1:n
for j=1:n
for k=1:n
C(i,j) = C(i,j) + A(i,k) * B(k,j);
end
end
end
end
function [C] = matTimesMat_column(A, B)
s = size(A);
n = s(1);
C = zeros(n);
for j=1:n
for k=1:n
C(:,j) = C(:,j) + B(k,j) * A(:,k);
end
end
end
function [C] = matTimesMat_outerProd(A, B)
s = size(A);
n = s(1);
C = zeros(n);
for j=1:n
C = C + A(:,j) * B(j,:);
end
end