使用matlab根据矩阵中出现的先前不同值计算固定值?

时间:2013-12-13 12:35:11

标签: matlab matrix

我在matlab中有一个列矩阵,如下所示:

8
8
8
8
6
6
6
6
6
7
7
7
7
7
7
6
6
6

值为8或7(随机顺序),后面跟着系列6 我想创建一个新列,我准确报告第1列的值,除了6,应该更改为67(如果之前的数字是6之前是7)或68(如果之前的数字是6之前是6) a 8)。此更改仅针对6进行,所有其他值的报告与第一列中的完全相同。得到的矩阵应为:

8  8
8  8
8  8
8  8
6  68
6  68
6  68
6  68
6  68
7  7
7  7
7  7
7  7
7  7
7  7
6  67
6  67
6  67

我试过像

这样的东西
matrix(matrix(:,1)==6,1) = 67

但这改变了67中的所有6并且没有区分在前6个之前是否有7或8

3 个答案:

答案 0 :(得分:3)

  1. 如果你不介意用一个小循环来迭代6的运行 - 值:

    aux = diff([a(:); NaN]==6); %// add a final NaN to make sure last run stops
    start = 1+find(aux==1); %// indices where runs of 6-values start
    stop = find(aux==-1); %// indices where runs of 6-values stop
    b = a; %// we'll now change some values
    for ii = 1:length(start)
        b(start(ii):stop(ii)) = 60+a(start(ii)-1);
    end
    result = [a b];
    

    正如@Dennis所指出的,如果7,8之外的数字可以在6之前,则此解决方案会自动处理。

  2. 你可以摆脱循环,但这需要一些复杂的事情。前四行与以前相同:

    aux = diff([a(:); NaN]==6); %// add a final NaN to make sure last run stops
    start = 1+find(aux==1); %// indices where runs of 6-values start
    stop = find(aux==-1); %// indices where runs of 6-values stop
    b = a; %// we'll now change some values
    w = a(start-1)==7; %// which runs of 6-values should be 67
    ind = any(bsxfun(@ge, 1:numel(a), start(w)) & bsxfun(@le, 1:numel(a), stop(w)),1); %// indices of those 6-values
    b(ind) = 67;
    w = a(start-1)==8; %// which runs of 6-values should be 68
    ind = any(bsxfun(@ge, 1:numel(a), start(w)) & bsxfun(@le, 1:numel(a), stop(w)),1); %// indices of those 6-values
    b(ind) = 68;
    result = [a b];
    

    如果除了7,8之外的数字可以在6之前,则每个数字需要三个新行。例如,对于9:

    w = a(start-1)==9; %// which runs of 6-values should be 69
    ind = any(bsxfun(@ge, 1:numel(a), start(w)) & bsxfun(@le, 1:numel(a), stop(w)),1); %// indices of those 6-values
    b(ind) = 69;
    

    或者,当然,使用可能数字的循环。

答案 1 :(得分:2)

这是一种方式:

%// Initialize the array
A = [A A];

%// Find the start/stop indices for all sixes
series     = diff(A(:,2)==6);
sixesStart = find( [false; series==1] );
sixesStop  = find( [series==-1; A(end,2)==6] );

%// Find the values just before the start of all sixes
prevValues = A([series==1; false],2);

%// Generate the new numbers
for ii = 1:numel(prevValues)
    A(sixesStart(ii):sixesStop(ii),2) = ...
        str2double([num2str(6) num2str(prevValues(ii))]);
end

答案 2 :(得分:1)

如果没有真正清晰的模式,您可能想要求助于一个简单的循环。

示例:

V = [1 2 7 7 6 8 6 9 6]';

V = [V V];
lastNonSix = 0;
for t  = 1:size(V,1)
  if V(t,1) ~= 6
    lastNonSix = V(t,1);
  elseif lastNonSix ==7 || lastNonSix ==8
    V(t,2) = lastNonSix + 60;
  end
end
V

这假设您不希望将9之后的6变为69.否则您只需将elsif变为else语句。