user2913990
user2913990

Reputation: 107

Matlab: Manipulation of Matrix and Storing them

How do I assign all the values of position in to a new variable?

A = [ -1   0  -2   0   0
       2   8   0   1   0
       0   0   3   0  -2
       0  -3   2   0   0
       1   2   0   0  -4];

  a=size(A);
  b=size(A);
  c=0;
  position=0;
  for i=1:a 
      for j=1:b 
          if A(i,j) ~=0
              c=c+1;
              position=position+1;
              S(c,:)=[position,i,j,A(i,j)];
          end
      end
  end

Result: S =

 1     1     1    -1
 2     1     3    -2
 3     2     1     2
 4     2     2     8
 5     2     4     1
 6     3     3     3
 7     3     5    -2
 8     4     2    -3
 9     4     3     2
10     5     1     1
11     5     2     2
12     5     5    -4

Something like position= 1 2 3 4 5 6 7 8 9 10 11 12

And the same thing for i

Upvotes: 0

Views: 72

Answers (2)

nispio
nispio

Reputation: 1744

I think that you would save yourself a lot of grief with the find function:

A = [ -1   0  -2   0   0
       2   8   0   1   0
       0   0   3   0  -2
       0  -3   2   0   0
       1   2   0   0  -4];

[I,J,V] = find(A);

Will put the (i,j) locations of the non-zero elements of in I and J respectively, with the values in V. If you really want the position vector you can just create it with position = 1:length(V);.

Upvotes: 2

David
David

Reputation: 8459

In your code, you ill always have c=position, so one must be redundant. At the end of the loop, you can pull out the values of position by doing S(:,1) which gives the first column of S. Likewise you can get the values of i by doing S(:,2). Is that what you are looking for?

Upvotes: 0

Related Questions