【问题标题】:Ratios in matrix | Matrix/Vector | if statement/loop |矩阵中的比率 |矩阵/向量 | if 语句/循环 |
【发布时间】:2018-09-03 12:22:51
【问题描述】:

我想知道你将如何解释下面的函数来使用矩阵而不是向量输入,基本上我只是在该列中找到所有超过某个值的值,然后将其相加并除以总行数来给我比率.下面是矢量输入,但我有点不知道如何用矩阵输入来完成。我应该改用logical 吗?

如果有超过 2 列,我认为我选择的方法不会起作用,但我希望它可以容纳任何大小。

function Ratio = ratiovector(Vector)

N = numel(Vector);
c=0

for a = 1:N

    if Vectors(a) >= 20
        c=c + 1;
    end
    end


Ratio = c/N;
end

矩阵输入

function Ratio = ratiovector2(Matrix)

rows = Matrix(:,1)
columns = Matrix(:,2)
c = 0
d = 0

for a = 1:rows
    for b =1:columns

    if Matrix(a) >= 20
        c= c + 1;
    if Matrix(b) >= 20
        d= d + 1;
    end
    end


Ratio = ?;
end

【问题讨论】:

    标签: matlab for-loop if-statement


    【解决方案1】:

    您在 cmets 中阐明,您希望每列中的元素数超过阈值,超过矩阵中的行数。

    这是一个快速的单线(阈值为 20):

    ratio = sum(M>20, 1) / size(M, 1);
    

    打破这个,我们有

        M > 20;                 % logical array which is 1 where M > 20, 0 otherwise
    sum(M > 20, 1);             % column-wise sum of the logical
    sum(M > 20, 1) / size(M,1)  % Divide the sum by the number of rows to get ratio.
    

    这适用于任何列向量或矩阵。

    例子:

    M = [10, 15, 20, 100
         21,  0, 21, 101
          0,  0, 21, 102];
    
    ratio = sum(M>20, 1) / size(M, 1);
    % >> ratio = [0.333..., 0.0, 0.666..., 1.0] = [1/3, 0/3, 2/3, 3/3]
    

    【讨论】:

      【解决方案2】:

      我不太清楚你想如何标准化你的比率,但下面的函数是一个起点,它适用于矩阵和向量。它使用逻辑索引而不是 for 循环,这可能会有更好的性能。

      M = [0  1  2  5  22 ; 
           32 1  1  7  22 ; 
           10 10 10 10 20];
      
      Ratio = ratiovector2(M)
      
      
      function Ratio = ratiovector2(Matrix)
      
          % This will give you a boolean matrix the same size of Matrix, with
          % true values where Matrix elements are higher than 20
          detected = Matrix > 20;
      
          % The ratio is "how many are over 20 in each column"
          Ratio = sum(detected) ./ size(Matrix,1);
      end
      

      如果你需要一个函数并且你喜欢单行,那么你去:

      ratiovector3 = @(Matrix)sum(Matrix > 20) ./ size(Matrix,1);
      
      Ratio = ratiovector3(M)
      

      【讨论】:

      • 是的,它将显示每列的许多元素的比例超过 20。编辑:例如:M 应该输出类似 [1/3 0/3 0/3 0/3 3/3]
      • 如果您不清楚,请发表评论以澄清,这有助于防止问题在 OP 澄清后出现多余的答案。当你知道你有答案时保存答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 2021-08-02
      • 2020-10-25
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多