在matlab中增加struct的字段值

increment fields values of struct in matlab

我想创建一个结构,其中包含一个字段,该字段的元素数量根据 n 的值变化为 n(n-1)/2

例如,如果 n=4s=struct('name', { {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, {3,4} })

我写了这段代码,但它只生成循环的最后一个值:

function [ b ] = Bwcl( cl )
n=size(cl,1);
for k=1:n-1
     for i=k:n-1
         b(k).name={num2str(k),num2str(i+1)};
     end
end

DomDev 正确回答了问题。但是,我想向您展示一种没有循环的方法:

n = 4;
ind = nchoosek(1:n, 2);
D = num2cell(ind, 2);
s = struct('name', D);

第二行代码使用 nchoosek to find all unique combinations of pairs from 1 up to n. This produces a matrix where each row is a unique pair of values. We then transform this into a cell array using num2cell,其中每对值占据元胞数组中的一个单元格,例如您在上面展示的方式。然后我们将此元胞数组输入 struct 以生成最终所需的结构。

如果您更喜欢单行(如果算上声明,则为两行 n):

n = 4;
s = struct('name', num2cell(nchoosek(1:n, 2), 2));

您忘记了密码计数器。问题是 b(k),它在同一位置重写了多次。使用如下所示的 b(counter),它可以工作。

counter = 0;
n=size(cl,1);
for k=1:n-1
     for i=k:n-1
         counter = counter + 1;
         b(counter).name={num2str(k),num2str(i+1)};
     end
end