简体   繁体   English

如何在Matlab中保存Matrix中的索引和值?

[英]How to save indices and values from Matrix in Matlab?

I have a 3x3 Matrix and want to save the indices and values into a new 9x3 matrix. 我有一个3x3矩阵,并希望将索引和值保存到一个新的9x3矩阵中。 For example A = [1 2 3 ; 4 5 6 ; 7 8 9] 例如A = [1 2 3 ; 4 5 6 ; 7 8 9] A = [1 2 3 ; 4 5 6 ; 7 8 9] A = [1 2 3 ; 4 5 6 ; 7 8 9] so that I will get a matrix x = [1 1 1; 1 2 2; 1 3 3; 2 1 4; 2 2 5; ...] A = [1 2 3 ; 4 5 6 ; 7 8 9]这样我就得到一个矩阵x = [1 1 1; 1 2 2; 1 3 3; 2 1 4; 2 2 5; ...] x = [1 1 1; 1 2 2; 1 3 3; 2 1 4; 2 2 5; ...] x = [1 1 1; 1 2 2; 1 3 3; 2 1 4; 2 2 5; ...] With my code I only be able to store the last values x = [3 3 9] . x = [1 1 1; 1 2 2; 1 3 3; 2 1 4; 2 2 5; ...]使用我的代码我只能存储最后的值x = [3 3 9]

A = [1 2 3 ; 4 5 6 ; 7 8 9]; 
x=[];
 for i = 1:size(A)
   for j = 1:size(A)
      x =[i j A(i,j)]
   end
 end

Thanks for your help 谢谢你的帮助

Vectorized approach 矢量化方法

Here's one way to do it that avoids loops: 这是避免循环的一种方法:

A = [1 2 3 ; 4 5 6 ; 7 8 9];
[ii, jj] = ndgrid(1:size(A,1), 1:size(A,2)); % row and column indices
vv = A.'; % values. Transpose because column changes first in the result, then row
x = [jj(:) ii(:) vv(:)]; % result

Using your code 使用你的代码

You're only missing concatenation with previous x : 你只缺少与之前的x连接:

A = [1 2 3 ; 4 5 6 ; 7 8 9];
x = [];
for i = 1:size(A)
  for j = 1:size(A)
    x = [x; i j A(i,j)]; % concatenate new row to previous x
  end
end

Two additional suggestions: 另外两项建议:

  • Don't use i and j as variable names , because that shadows the imaginary unit. 不要将ij用作变量名 ,因为它会影响虚构单位。
  • Preallocate x instead of having it grow in each iteration, to increase speed. 预分配 x而不是在每次迭代中增长,以提高速度。

The modified code is: 修改后的代码是:

A = [1 2 3 ; 4 5 6 ; 7 8 9];
x = NaN(numel(A),3); % preallocate
n = 0;
for ii = 1:size(A)
  for jj = 1:size(A)
    n = n + 1; % update row counter
    x(n,:) = [ii jj A(ii,jj)]; % fill row n
  end
end

I developed a solution that works much faster. 我开发了一种工作速度更快的解决方案。 Here is the code: 这是代码:

% Generate subscripts from linear index
[i, j] = ind2sub(size(A),1:numel(A));

% Just concatenate subscripts and values
x = [i' j' A(:)];

Try it out and let me know ;) 尝试一下,让我知道;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM