【问题标题】:Getting value and index of array matlab获取数组matlab的值和索引
【发布时间】:2013-11-26 10:44:56
【问题描述】:

我在 Matlab 中有一个数组,比如说 (256, 256)。现在我需要构建一个新的维度数组 (3, 256*256),每行包含值和原始数组中值的索引。即:

test = [1,2,3;4,5,6;7,8,9]

test =

 1     2     3
 4     5     6
 7     8     9

结果我需要:

[1, 1, 1; 2, 1, 2; 3, 1, 3; 4, 2, 1; 5, 2, 2; and so on]

有什么想法吗? 提前致谢!

【问题讨论】:

    标签: arrays matlab


    【解决方案1】:

    你想要的是meshgrid的输出

    [C,B]=meshgrid(1:size(test,1),1:size(test,2))
    M=test;
    M(:,:,2)=B;
    M(:,:,3)=C;
    

    【讨论】:

    • 对不起,我是 matlab 的新手,我想我搞砸了这个问题。让我换个说法,我有一个 256x256 矩阵中的图像,需要获取图像坐标的“列表”以及坐标中的值。因此,如果矩阵的位置 1,1 包含值 145,则结果数组的第一行将是 [145, 1, 1] 等等。
    【解决方案2】:

    这是我想出来的

    test = [1,2,3;4,5,6;7,8,9]; % orig matrix
    
    [m, n] = size(test); % example 1, breaks with value zero elems
    o = find(test);
    test1 = [o, reshape(test, m*n, 1), o]
    

    经过的时间是 0.004104 秒。

    % one liner from above
    % (depending on data size might want to avoid dual find calls)
    test2=[ find(test) reshape(test, size(test,1)*size(test,2), 1 ) find(test)]
    

    经过的时间是 0.008121 秒。

    [r, c, v] = find(test); % just another way to write above, still breaks on zeros
    test3 = [r, v, c]
    

    经过的时间是 0.009516 秒。

    [i, j] =ind2sub([m n],[1:m*n]); % use ind2sub to build tables of indicies
                                    % and reshape to build col vector
    test4 = [i', reshape(test, m*n, 1), j']
    

    经过的时间是 0.011579 秒。

    test0 = [1,2,3;0,5,6;0,8,9]; % testing find with zeros.....breaks
    % test5=[ find(test0) reshape(test0, size(test0,1)*size(test0,2), 1 ) find(test0)] % error in horzcat
    
    [i, j] =ind2sub([m n],[1:m*n]); % testing ind2sub with zeros.... winner
    test6 = [i', reshape(test0, m*n, 1), j']
    

    经过的时间是 0.014166 秒。

    从上面使用网格网格: 经过的时间是 0.048007 秒。

    【讨论】:

    • 所以,如果你没有零,我建议使用 find。否则ind2sub?对于非常小的数据集,请记住这一点。您应该tic toc 了解它如何随您的数据扩展。
    猜你喜欢
    • 2013-08-10
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    相关资源
    最近更新 更多