在循环期间将值存储到单元阵列中:Matlab

时间:2016-12-13 08:44:59

标签: matlab cell-array

我尝试过以下代码:

V = [0.5 0.1 0.1 0.9 0.5 0.1 0.9 0.9 0.5];
S = {'A','B','C'};
N = sqrt(numel(V));
M = reshape(V, N, N).';

for i=1:N
    for j=i+1:N
        if M(i,j)<M(j,i)
            %print(S(i),'<',S(j)) % A< B, A<C, C<B
            order1=S{i};
            order2=S{j};
            fprintf('orders:\n%s%s \n', order1,order2);
            S1(i,:)=(order1,order2) % bug is here
            % It should be the same output with S1={'AB', 'BC', 'AC'}
        else
            order1=S{i};
            order2=S{j};
            fprintf('orders:\n%s%s', order2,order1);
            S2(j,:)=(order2,order1)
        end
    end
end

我想将order1order2的值存储到S1单元格数组中。但是在执行此操作时,我的代码中似乎存在一个错误。我的循环正确地将'AB', 'AC', 'BC'输出到命令窗口,但最后输出S1 = {'AC'; 'BC'}

如何获得正确的S1S1 = {'AB', 'BC', 'AC'}与{{1}}的输出相同?

1 个答案:

答案 0 :(得分:0)

这里有2个问题

  1. 您对单元格的分配不是很正确,您应该替换

    S1(i,:)=(order1,order2)
    

    S1{i} = [order1, order2];
    

    方括号将字符order1order2连接成一个字符串,然后花括号将该字符串指定为单元格数组元素。

  2. 您的输出结构是S1 = {'AC'; 'BC'},但您想要的输出(由fprintf语句显示)是:

    >> orders: AB
    >> orders: AC
    >> orders: BC
    

    这是因为i = 1 'AB''AC'两种情况都是S1,因此V = [0.5 0.1 0.1 0.9 0.5 0.1 0.9 0.9 0.5]; S = {'A','B','C'}; N = sqrt(numel(V)); M = reshape(V, N, N).'; S1 = {}; S2 = {}; for i = 1:N for j = i+1:N if M(i,j)<M(j,i) %print(S(i),'<',S(j)) % A< B, A<C, C<B order1=S{i}; order2=S{j}; fprintf('orders:\n%s%s \n', order1,order2); % append item to the cell array S1 = [S1, {[order1,order2]}]; else order1=S{i}; order2=S{j}; fprintf('orders:\n%s%s', order2,order1); S2 = [S2, {[order2,order1]}]; end end end % S1 = {'AB', 'AC', 'BC'} 中的第一个元素会被覆盖!相反,请考虑通过连接来构建单元格。这已显示在您的more recent question

  3. 更新了代码

    class Continent(models.Model):
        continent = models.CharField(max_length=30)
    
    class Country(models.Model):
        country = models.CharField(max_length=30)
        continent = models.ForeignKey(Continent)
    
    class City(models.Model):
        city = models.CharField(max_length=30)
        country = models.ForeignKey(Country)
    
    class Person(models.Model):
        name = models.CharField(max_length=30)
        continent = models.ForeignKey(Continent)
        country = models.ForeignKey(Country)
        city = models.ForeignKey(City)