MATLAB -给定一个矩阵,输出常数因子和新矩阵



给定一个矩阵,输出常数因子和新矩阵。该常数是一个整数,可以是实数也可以是虚数。下面是一些例子:

i = sqrt(-1);
M1 = [2 4 6; 8 10 12];
% output:
% Factor: 2
% Matrix: [1 2 3; 4 5 6];
M2 = [1*i 4*i 5*i; 8*i 7*i 12*i];
% output:
% Factor: i
% Matrix: [1 4 5; 8 7 12]
M3 = [1 2 5; 4 8 1]
% output:
% Factor: 1
% Matrix: [1 2 5; 4 8 1]

您可以像下面这样定义自定义函数f

function [Factor, Matrix] = f(M)
if all(imag(M)~=0)
s = 1j;
else
s = 1;
end
V = unique(M(:)/s);
Factor = V(1);
for k = 2:length(V)
Factor = gcd(Factor,V(k));
end
Factor = Factor*s;
Matrix = M./Factor;
end

,你会

>> [factor, matrix] = f(M1)
factor =
2

matrix =
1     2     3
4     5     6
>> [factor, matrix] = f(M2)
factor =
0.0000 + 1.0000i

matrix =
1     4     5
8     7    12
>> [factor, matrix] = f(M3)
factor =
1

matrix =
1     2     5
4     8     1
>> [factor, matrix] = f([2,3])
factor =
1

matrix =
2     3

最新更新