一本值得百炼的计算数学书籍
突发奇想,这次把将Golub的矩阵计算代码封装在matlab 函数文件中和cuda lib中,以后在小项目中可以使用自己的库了^_^。
书中代码是为普通代码场景预备的,并不适合直接封装成函数,但是可以在函数中使用它,虽然会略显不自然。
algorithm1.1.1:
function c = mc_innerproduct(x,y)
%Matrix Computations 4th edition Chapter1 algorithm 1.1.1
c =0;
for i=1:numel(x)
c=c+x(i)*y(i);
end
end
调用方法:
>> edit mc_innerproduct.m %将上述代码ctl+c ctl+v ctl+s 后调用mc_innerproduct
>> vect1=[1,2,3]
>> vect2=[1,1,1]
>> innV1V2 = mc_innerproduct(vect1,vect2)
algorithm 1.1.2:
function y = mc_saxpy(y,a,x)
%Matrix Computations 4th edition Chapter1 algorithm 1.1.2
for i= 1:numel(y)
y(i)=y(i)+a*x(i);
end
end
调用方法:
>> vect1=mc_saxpy(vect1,2,vect2) % 实现 vect1 = vect1 + a*vect2
algorithm1.1.3:
function y=mc_gaxpy_row(y,A,x)
%Matrix Computations 4th edition Chapter1 algorithm 1.1.3 gaxpy_row
m = numel(y);
n = numel(x);
for i=1:m
for j=1:n
y(i)=y(i)+A(i,j)*x(j);
end
end
end
调用方式:
>> y=[1 2 3]
>> x=[1; 1; 1; 1]
>> A=[1 1 1 1;2 2 2 2;3 3 3 3]
>> c=mc_gaxpy_row(y,A,x)
>> c
c =
5 10 15
>>
algorithm1.1.4
function y=mc_gaxpy_column(y,A,x)
%Matrix Computations 4th edition Chapter1 algorithm 1.1.4
m=numel(y);
n=numel(x);
for j=1:n
for i=1:m
y(i)=y(i)+A(i,j)*x(j);
end
end
end
调用方式:
>> y=[1 2 3]
>> x=[1; 1; 1; 1]
>> A=[1 1 1 1;2 2 2 2;3 3 3 3]
>> d=mc_gaxpy_column(y,A,x)
d =
5 10 15
>>
algorithm1.1.5:
function C=mc_Mcecpab(C,A,B)
%Matrix Computations 4th edition Chapter1 algorithm 1.1.5 Matrix:ABC C:mxn A:mxr B:rxn C=C+AB
m = size(A,1)
r = size(A,2)
rb = size(B,1)
n = size(B,2)
mc=size(C,1);
nc=size(C,2);
if(rb ~= r || m~=mc || n~=nc)
error('The size of input matrixs do not match eachother.');
end
for i=1:m
for j=1:n
for k=1:r
C(i,j)=C(i,j)+A(i,k)*B(k,j);
end
end
end
调用方式:
>> M1=[1 1 1 ;1 1 1 ; 1 1 1 ;1 1 1 ]
>> M2=[1 1; 1 1; 1 1; 1 1;]
>> M3=[1 1 1;1 1 1]
>> M4=mc_Mcecpab(M1,M2,M3)
M4 =
3 3 3
3 3 3
3 3 3
3 3 3
>>
跟1.1.5很像,只是把最内层的循环求点积更改为matlab的1xn矩阵和nx1矩阵的矩阵乘积,结果为标量数。
algorithm1.1.6:
function C=mc_Mcecpab_innerp(C,A,B)
%Matrix Computations 4th edition Chapter1 algorithm 1.1.6 Matrix:ABC C:mxn A:mxr B:rxn C=C+AB
m = size(A,1)
r = size(A,2)
rb = size(B,1)
n = size(B,2)
mc=size(C,1);
nc=size(C,2);
if(rb ~= r || m~=mc || n~=nc)
error('The size of input matrixs do not match eachother.');
end
for i=1:m
for j=1:n
C(i,j)=C(i,j)+A(i,:)*B(:,j);
end
end
调用方式同1.1.5:
>> M4=mc_Mcecpab_innerp(M1,M2,M3)
M4 =
3 3 3
3 3 3
3 3 3
3 3 3
>>