【问题标题】:Importing numerical vectors and strings into a MATLAB matrix将数值向量和字符串导入 MATLAB 矩阵
【发布时间】:2012-01-27 01:56:16
【问题描述】:

我有以下数据结构(存储为 CSV):

Sub Cond Pic Vals  
s101 A pic1 [1,3,5,1,-2,5]  
s101 A pic2 [1,-2,5,0,2,1]  
s101 B pic1 [2,4,7,0,1,-3]  
s101 B pic2 [3,-1,1,1,6,1]  
s102 A pic1 [1,7,7,3,-1,5]  
s102 A pic2 [2,8,7,0,3,-4]  

...等

我想遍历主题和条件以关联 pic1 和 pic2 之间的值向量。

在 python 中,我会将它们组织为字典列表,但我不确定 MATLAB 中的类似/最佳结构是什么。在 MATLAB 中导入和组织这些数据的最佳方式是什么?

【问题讨论】:

    标签: matlab csv vector structure import


    【解决方案1】:

    例如,您可以这样做:

    xp.txt:

    Sub Cond Pic Vals  
    s101 A pic1 [1,3,5,1,-2,5]  
    s101 A pic2 [1,-2,5,0,2,1]  
    s101 B pic1 [2,4,7,0,1,-3]  
    s101 B pic2 [3,-1,1,1,6,1]  
    s102 A pic1 [1,7,7,3,-1,5]  
    s102 A pic2 [2,8,7,0,3,-4]
    

    matlab 脚本:

    nValue=6; %%%%% or 90
    vals=cell(1,nValue);   
    [sub cond pic vals{:}]=textread('xp.txt',['%s %s %s [%f' repmat(',%f',1,nValue-1) ']'],'headerlines',1)
    vals=horzcat(vals{:})
    for s = unique(sub)'
      for c = unique(cond)'
         index=(strcmp(sub,s{1})&strcmp(cond,c{1}));
         display(['sub: ' s{1} '; cond: ' c{1} ])
         resu1=vals(index & strcmp(pic,'pic1'),:)
         resu2=vals(index & strcmp(pic,'pic2'),:)
         %%%% computation of the correlation
      end
    end
    

    结果:

    sub: s101; cond: A
    resu1 =
         1     3     5     1    -2     5
    resu2 =
         1    -2     5     0     2     1
    sub: s101; cond: B
    resu1 =
         2     4     7     0     1    -3
    resu2 =
         3    -1     1     1     6     1
    sub: s102; cond: A
    resu1 =
         1     7     7     3    -1     5
    resu2 =
         2     8     7     0     3    -4
    sub: s102; cond: B
    resu1 =
       Empty matrix: 0-by-6
    resu2 =
       Empty matrix: 0-by-6
    

    PS:

    还有很多其他的可能性取决于你想要什么

    【讨论】:

    • 有什么方法可以避免预先指定值,例如 textread('xp.txt','%s %s %s [%f,%f,%f,%f,% f,%f]'...)?我简化了这个例子的向量;实际上,向量中有超过 90 个值...
    • 好的,我编辑了。您只需将 nValue=6; 替换为 nValue=90 即可:P
    猜你喜欢
    • 2016-07-16
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多