【问题标题】:Indices of constant consecutive values in a matrix, and number of constant values矩阵中常数连续值的索引,以及常数值的数量
【发布时间】:2014-11-09 09:41:22
【问题描述】:

我有一个矩阵,其中连续的常数值随机分布在整个矩阵中。我想要连续值的索引,此外,我想要一个与原始矩阵大小相同的矩阵,其中连续值的数量存储在连续值的索引中。例如

  original_matrix = [1 1 1;2 2 3; 1 2 3];

  output_matrix = [3 3 3;2 2 0;0 0 0];

我一直在努力寻找解决这个问题的方法。它与气象数据质量控制相关。例如,如果我有一个来自多个传感器的温度数据矩阵,并且我想知道哪些天具有恒定的连续值,以及有多少天是恒定的,那么我可以将数据标记为可能有错误。

温度矩阵是天数 x 站数,我想要一个输出矩阵,它也是天数 x 站数,其中连续值被标记为如上所述。

如果您对此有解决方案,请提供!谢谢。

【问题讨论】:

  • 为了保持一致,你的output_matrix 中的0s 不应该是1s 吗?如果连续值发生变化,则始终有 1 个恒定连续值。
  • @hitzg 是的,这很好,实际上很好。使用 1 而不是 0 可能会更好。感谢您的反馈!

标签: matlab matrix run-length-encoding


【解决方案1】:

针对这类问题,我做了自己的实用函数runlength

function RL = runlength(M)
% calculates length of runs of consecutive equal items along columns of M

% work along columns, so that you can use linear indexing

% find locations where items change along column
jumps = diff(M) ~= 0;

% add implicit jumps at start and end
ncol = size(jumps, 2);
jumps = [true(1, ncol); jumps; true(1, ncol)]; 

% find linear indices of starts and stops of runs
ijump = find(jumps);
nrow = size(jumps, 1);
istart = ijump(rem(ijump, nrow) ~= 0); % remove fake starts in last row
istop = ijump(rem(ijump, nrow) ~= 1); % remove fake stops in first row
rl = istop - istart;
assert(sum(rl) == numel(M))

% make matrix of 'derivative' of runlength
% don't need last row, but needs same size as jumps for indices to be valid
dRL = zeros(size(jumps)); 
dRL(istart) = rl;
dRL(istop) = dRL(istop) - rl;

% remove last row and 'integrate' to get runlength
RL = cumsum(dRL(1:end-1,:));

它只适用于列,因为它使用linear indexing。由于您想沿行执行类似的操作,因此您需要来回转置,因此您可以将其用于您的情况,如下所示:

>> original = [1 1 1;2 2 3; 1 2 3];
>> original = original.';  % transpose, since runlength works along columns
>> output = runlength(original);
>> output = output.';  % transpose back
>> output(output == 1) = 0;  % see hitzg's comment
>> output

output =

     3     3     3
     2     2     0
     0     0     0

【讨论】:

  • 效果很好!现在我看到了解决方案 - 您需要在连续值的索引之后使用那些负 1(-1),以便 cumsum 得到“重置”。我发现的大多数运行长度编码示例都不会返回存储在相应索引中的原始运行长度。谢谢!
猜你喜欢
  • 2021-08-12
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2010-12-22
相关资源
最近更新 更多