Skip to content

Instantly share code, notes, and snippets.

@sunho
Created October 6, 2023 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunho/fad50b689f63d1b938e9d0f503ae4e76 to your computer and use it in GitHub Desktop.
Save sunho/fad50b689f63d1b938e9d0f503ae4e76 to your computer and use it in GitHub Desktop.
MATH 170A HW0
A = rand(9);
x = rand(9,1);
disp("My implementation:");
disp(mul_vec_by_mat(A,x));
disp("Matlab implementation:");
disp(A*x);
function Ax = mul_vec_by_mat(A, x)
[m, n] = size(A);
if length(x) ~= n
error('dimenstion mismatch!');
end
Ax = zeros(m,1);
for i = 1:m
for j = 1:n
Ax(i) = Ax(i) + A(i,j) * x(j);
end
end
end
A = rand(9,4);
B = rand(4,6);
disp("My implementation:");
disp(mul_mat_by_mat(A,B));
disp("Matlab implementation:");
disp(A*B);
function C = mul_mat_by_mat(A, B)
[m, n] = size(A);
[n_, p] = size(B);
if n ~= n_
error('dimenstion mismatch!');
end
C = zeros(m,p);
for k = 1:n % k first for L1 cache friendly
for j = 1:p % j needs to go before i since matlab uses "column major memory layout"
for i = 1:m
C(i,j) = C(i,j) + A(i,k) * B(k,j);
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment