在MATLAB中使用数组中的值填充矩阵

时间:2018-10-14 14:21:49

标签: matlab

我有以下数组,

Names = [string('abc') string('def') string('ghi') string('jkl')]
SubName1 = [string('abc') string('jkl')]
SubValue1 = [-1 1]
SubName2 = [string('ghi') string('jkl')]
SubValue2 = [-2 1]

名为SubValue1的数组包含与名为SubName1的数组中的键(字符串)相对应的值。我想将SubNameNames进行比较并创建一个映射键值对的矩阵,如下所示:

RowName  SubName1 SubName2
abc          -1       0
def           0       0 
ghi           0      -2
jkl           1       1

要获得上述矩阵,我正在尝试以下方法,

Index1 = find(ismember(Names,SubName1))
Index2 = find(ismember(Names,SubName2))

>>Index1 = [1 4];
>>Index2 = [3 4];

我不确定如何从这里继续。本质上,我试图用SubValue中存在的索引处的键SubNames的值Index填充矩阵的列。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您快到了。创建空向量,并使用带有Index1Index2的逻辑索引来插入SubValue1SubValue2中的值:

>> Names = [string('abc') string('def') string('ghi') string('jkl')];
>> SubName1 = [string('abc') string('jkl')];
>> SubValue1 = [-1 1];
>> SubName2 = [string('ghi') string('jkl')];
>> SubValue2 = [-2 1];

>> Index1 = find(ismember(Names,SubName1))
>> Index2 = find(ismember(Names,SubName2))

>> SubName1 = zeros(numel(Names),1);
>> SubName2 = zeros(numel(Names),1);

>> SubName1(Index1) = SubValue1;
>> SubName2(Index2) = SubValue2;

>> t = table(Names.',SubName1,SubName2);
>> t.Properties.VariableNames(1) = {'RowName'}

t =

  4×3 table

    RowName    SubName1    SubName2
    _______    ________    ________

     "abc"        -1           0   
     "def"         0           0   
     "ghi"         0          -2   
     "jkl"         1           1   

请注意,通常不建议为变量SubName1SubName2命名。您会发现this个MATLAB答案很有用。