【问题标题】:Extracting corresponding values of particular number from a large matrix从大矩阵中提取特定数字的对应值
【发布时间】:2020-01-16 22:53:12
【问题描述】:

我有一个 2x5000 矩阵,其中包含刺激值(1 到 7)和相应的响应。刺激值随机分散在数据中。 喜欢:

2   0
3   1
3   1
1   1
7   0
6   0
7   1
6   1
1   0
1   0
7   1
6   1
4   1

我需要计算每个刺激值的响应平均值(例如,我需要 7 个平均值)。

但我不知道如何分离这些值以及它在不同变量中的对应值(例如如何提取 6 和它的对应数据)。

第二个类似的矩阵变得越来越棘手,在原始值上增加了噪声,我希望从中提取 1 到 1.9,... 6 到 6.9 和相应的值。

我正在尝试 find(data_experiment == 4) (例如),它返回我的 2x5000 矩阵中所有 4 的位置,但我不知道如何提取相应的数据。

还有什么比“找到”更好的吗?

谁能建议可以使用哪些功能?

【问题讨论】:

    标签: matlab matrix indexing extract


    【解决方案1】:

    您可以使用accumarray 函数来解决它:

    这是一个示例代码:

    D = [2   0
         3   1
         3   1
         1   1
         7   0
         6   0
         7   1
         6   1
         1   0
         1   0
         7   1
         6   1
         4   1];
    
    %Compute sums: 
    %Result: S(1) sumSecCol(where FirstCol = 1), S(2) = sumSecCol(where FirstCol = 2), S(3) = sumSecCol(where FirstCol = 3), 
    S = accumarray(D(:,1), D(:,2));
    
    %Compute count (replace D(:,2) with "1"s):
    C = accumarray(D(:,1), ones(size(D,1), 1));
    
    %Remove zeros from C - to avoid division by zero
    C = max(C, 1);
    
    %Compute mean
    M = S ./ C;
    

    结果:

    M =
    
        0.3333
             0
        1.0000
        1.0000
             0
        0.6667
        0.6667
    

    对于“1 to 1.9, ... 6 to 6.9”的噪声情况,可以使用floor函数:

    D = floor(D);
    

    1 到 1.9999 到 1,2 到 2.9999 到 2...

    看起来round是更多的字幕,但你描述的操作适用于floor


    这是一个使用for循环的解决方案,不使用accumarray

    S = zeros(7, 1);
    C = zeros(7, 1);
    
    D1 = D(:, 1); %First column
    D2 = D(:, 2); %Second column
    
    for i = 1:7
        S(i) = sum(D2(D1 == i));
        C(i) = sum(D1 == i);
    end
    
    M = S ./ max(C, 1);
    

    建议使用logical indexing,而不是使用find

    【讨论】:

    • M = accumarray(D(:,1), D(:,2), [], @mean);
    • 谢谢,我从您之前的一个答案中了解到accumarray 功能。我还有很多东西要学...
    • 老实说,非常感谢你们,伙计们!我非常感谢您的回复和向您学习的机会。
    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多