将当前迭代与之前的迭代进行比较,MATLAB

Compare current iteration with previous one, MATLAB

如何比较循环中的当前迭代与前一个迭代?

例如,我想查看矩阵中作为结构一部分的元素是否低于同一元素,但来自上一次迭代(显然这些值不同,但相同的元素,只是不同的迭代)。为了更清楚,我需要调用矩阵元素 mystruct(h).field(j,1) 并查看该元素是否低于 mystruct(h-1).field(j,1)

a=rand(20,1);
field = 'field';
for h=1:20
    value = 1.4*rand(20,1);
    value1 = zeros(20,1);
    mystruct(h) = struct(field,value);
    NEWstruct(h) = struct(field,value1);
end

for j=1:20
    if mystruct(1).field(j,1)<a(j,1)
        NEWstruct(1).field(j,1)=mystruct(1).field(j,1);
    else
        NEWstruct(1).field(j,1)=a(j,1);
    end
end

现在我必须查看下一次迭代 mystruct(2).field(j,1) 是否低于上一次迭代 NEWstruct(1).field(j,1),如果是,则将其值分配给 NEWstruct(2).field(j,1)。如果不是,那么它应该等于 mystruct(1).field(j,1)

在一般情况下,您可以使用以下数组:

field_data = cat(3,mystruct.field);

greater = diff(field_data, [], 3)>0;

现在 greater 是一个 3D 数组,由大小为 fieldsize(mystruct)-1 层的二维数组组成。每一层对应于每次迭代中的一个变化。因此,如果值增加,则您有 1,如果值减少,则有 0。例如你可能有这样的东西:

field_data(:,:,1) =

    0.0358    0.4735    0.6074
    0.1759    0.1527    0.1917
    0.7218    0.3411    0.7384


field_data(:,:,2) =

    0.2428    0.7655    0.0911
    0.9174    0.1887    0.5762
    0.2691    0.2875    0.6834


field_data(:,:,3) =

    0.5466    0.6476    0.9452
    0.4257    0.6790    0.2089
    0.6444    0.6358    0.7093


greater(:,:,1) =

     1     1     0
     1     1     1
     0     0     0


greater(:,:,2) =

     1     0     1
     0     1     0
     1     1     1

使用此数组,您只需检查每个可能更改的正确值。

在您的特定情况下,如果您想要的只是将最小值 min(mystuct(h-1).field(j),mystuct(h).field(j)) 分配给 NEWsctruct(h).field(j),您可以简单地遍历所有值并添加以下代码:

for h=2:length(mystruct)
    for j=1:20
        NEWstruct(h).field(j) = min(mystruct(h-1).field(j),mystruct(h).field(j));
    end
end

或使用矢量化形式:

field_data = cat(2,mystruct.field);           % Gather the whole data in a matrix
minimum = min(field_data(:,2:end),field_data(:,1:end-1));  % Get the proper values (as a matrix)
NEWstruct(2:end) = cell2struct(num2cell(minimum,1),field,1);  % Assign the values to the struct