我在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]
有什么想法吗? 提前谢谢!
答案 0 :(得分:3)
您想要的是meshgrid
[C,B]=meshgrid(1:size(test,1),1:size(test,2))
M=test;
M(:,:,2)=B;
M(:,:,3)=C;
答案 1 :(得分:1)
这就是我想出的
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秒。
使用上面的meshgrid: 经过的时间是0.048007秒。