Piotr De
Piotr De

Reputation: 157

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. For example 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; ...] With my code I only be able to store the last values 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

Upvotes: 1

Views: 643

Answers (2)

Dario
Dario

Reputation: 153

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 ;)

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112679

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:

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.
  • Preallocate x instead of having it grow in each iteration, to increase speed.

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

Upvotes: 3

Related Questions