【问题标题】:MATLAB - Given a matrix, output the constant factor and the new matrixMATLAB - 给定一个矩阵,输出常数因子和新矩阵
【发布时间】:2021-08-30 21:23:16
【问题描述】:

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

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]

【问题讨论】:

  • 您可以使用gcd。它返回最大公约数。但是,此函数只需要两个标量,因此您必须遍历矩阵中的所有元素。它也只适用于整数,但您可以检查是否所有数字都是虚数,然后可以手动分解出 i。

标签: matlab matrix


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 2013-06-18
    • 1970-01-01
    • 2012-04-10
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    相关资源
    最近更新 更多