Matlab 矩阵中连续常量值的索引和常量值的数量

Matlab 矩阵中连续常量值的索引和常量值的数量,matlab,matrix,run-length-encoding,Matlab,Matrix,Run Length Encoding,我有一个常数连续值随机分布在整个矩阵中的矩阵。我想要连续值的索引,而且,我想要一个与原始矩阵大小相同的矩阵,其中连续值的数量存储在连续值的索引中。比如说 original_matrix = [1 1 1;2 2 3; 1 2 3]; output_matrix = [3 3 3;2 2 0;0 0 0]; 我为找到解决这个问题的办法而苦苦挣扎。它对气象数据质量控制具有相关性。例如,如果我有一个来自多个传感器的温度数据矩阵,我想知道哪些天的连续值是恒定的,有多少天是恒定的,这样我就可以

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

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

  output_matrix = [3 3 3;2 2 0;0 0 0];
我为找到解决这个问题的办法而苦苦挣扎。它对气象数据质量控制具有相关性。例如,如果我有一个来自多个传感器的温度数据矩阵,我想知道哪些天的连续值是恒定的,有多少天是恒定的,这样我就可以将数据标记为可能有故障

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


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

对于此类问题,我制作了自己的实用函数
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,:));
它只沿列工作,因为它使用。由于您希望沿行执行类似的操作,因此需要来回转置,以便可以将其用于如下情况:

>> 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

为了保持一致,您的
输出矩阵
中的
0
s不应该是
1
s吗?如果连续值发生变化,则始终存在一个常量连续值。@hitzg是的,这很好,事实上这是一个很好的观点。最好是1而不是0。谢谢你的反馈!很好!现在我看到了解决方案-您需要在连续值的索引之后使用负1(-1),以便cumsum得到“重置”。我发现的大多数游程编码示例都不会返回存储在相应索引中的原始游程。非常感谢。