Matlab生成哈達瑪矩陣函數hadamard()的C語言實現
- matlab源代碼
- C語言實現
閱讀之前注意:
本文閱讀建議用時:34min
本文閱讀結構如下表:
項目 | 下屬項目 | 測試用例數量 |
---|---|---|
Matlab源代碼 | 無 | 1 |
C語言實現 | 無 | 1 |
Matlab源代碼
參考以下代碼1:
function H = hadamard(n,classname)
%HADAMARD Hadamard matrix.
% HADAMARD(N) is a Hadamard matrix of order N, that is,
% a matrix H with elements 1 or -1 such that H'*H = N*EYE(N).
% An N-by-N Hadamard matrix with N > 2 exists only if REM(N,4)=0.
% This function handles only the cases where N, N/12 or N/20
% is a power of 2.
%
% HADAMARD(N,CLASSNAME) produces a matrix of class CLASSNAME.
% CLASSNAME must be either 'single' or 'double' (the default).
% Nicholas J. Higham
% Copyright 1984-2005 The MathWorks, Inc.
% Reference:
% S. W. Golomb and L. D. Baumert, The search for Hadamard matrices,
% Amer. Math. Monthly, 70 (1963) pp. 12-17.
if nargin < 2, classname = 'double'; end
[f,e] = log2([n n/12 n/20]);
k = find(f==1/2 & e>0);
if min(size(n)) > 1 || isempty(k)
error(message('MATLAB:hadamard:InvalidInput'));
end
e = e(k)-1;
if k == 1 % N = 1 * 2^e;
H = ones(classname);
elseif k == 2 % N = 12 * 2^e;
H = [ones(1,12,classname); ones(11,1,classname) ...
toeplitz([-1 -1 1 -1 -1 -1 1 1 1 -1 1],[-1 1 -1 1 1 1 -1 -1 -1 1 -1])];
elseif k == 3 % N = 20 * 2^e;
H = [ones(1,20,classname); ones(19,1,classname) ...
hankel([-1 -1 1 1 -1 -1 -1 -1 1 -1 1 -1 1 1 1 1 -1 -1 1], ...
[1 -1 -1 1 1 -1 -1 -1 -1 1 -1 1 -1 1 1 1 1 -1 -1])];
end
% Kronecker product construction.
for i = 1:e
H = [H H
H -H]; %#ok
end
C語言實現
此處僅給出哈達瑪矩陣列數爲2的N次方的實現2:
參考以下代碼
int ** myHardmard(int n)//僅產生簡單的哈達瑪矩陣
{
int i = 0;
int j = 0;
int k = 0;
int findFlag = 0;
int finalI = 0;
int nLimit = (int)pow(2.0, 10.0);
if (n>nLimit)
{
printf("無法產生那麼大的哈達瑪矩陣,請手動關閉本程序\n");
system("pause");
}
for (i = 0; i <= 10; i++)
{
if (n == myPow(2,i))
{
findFlag = 1;
finalI = i;
break;
}
}
if (findFlag != 1)
{
printf("你輸入的哈達瑪矩陣列數n不是2的N次方,請手動關閉本程序\n");
system("pause");
}
int **H = (int **)malloc(n*sizeof(int *));
for (i = 0; i < n; i++)
H[i] = (int *)malloc(n*sizeof(int));
int row = myPow(2, finalI);
int col = row;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (i == 0 && j == 0)
H[i][j] = 1;
else for (k = 0; k <= 10; k++)
{
int tmpLimit = myPow(2, k);
if ((i >= tmpLimit) && (j >= tmpLimit))
{
H[i][j] = -H[i - tmpLimit][j - tmpLimit];
//break;
}
if ((i >= tmpLimit) && (j < tmpLimit))
{
H[i][j] = H[i - tmpLimit][j];
//break;
}
if ((i<tmpLimit) && (j >= tmpLimit))
{
H[i][j] = H[i][j - tmpLimit];
//break;
}
}
}
}
printf("生成的哈達瑪矩陣是:\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%-3d ", H[i][j]);
}
printf("\n");
}
printf("\n");
return H;
}
事實上,以上代碼還可以拓展和簡化,功能上已經實現基本的哈達瑪矩陣了。改進算法將在以後添加。