Skullgreymon
Skullgreymon

Reputation: 193

Subsetting array in Matlab

Well, I want to change the zero elements, for example, (that they are zeros is not the point) and I am using this code, but when I'll go to subset it doesn´t do it well.

matrix = [ -1 1 0; 2 0 -2; 0 3 -3]
[rows,cols] = find(matrix==0)


matrix =
    -1     1     0
     2     0    -2
     0     3    -3
rows =
     3
     2
     1
cols =
     1
     2
     3


matrix(rows,cols)
ans =
     0     3    -3
     2     0    -2
    -1     1     0

why is this returning the entire matrix when is it only three single elements?

So if I do matrix(rows,cols)=1 it returns the entire matrix as 1 and not only the zero elements.

Upvotes: 0

Views: 769

Answers (1)

Dima Chubarov
Dima Chubarov

Reputation: 17169

MATLAB syntax provides several options to access non-consecutive elements in an array.

One way to solve your problem would be to use linear indexing.

Let

matrix = [ -1 1 0; 2 0 -2; 0 3 -3]

and

[rows,cols] = find(matrix == 0).

Then

sub2ind(size(matrix),rows,cols)

returns the linear indices of the selected elements, i.e. the vector [3;5;7].

Now

matrix(sub2ind(size(matrix),rows,cols)) = 1

would produce

matrix =

  -1   1   1
   2   1  -2
   1   3  -3

Exactly as you would expect.

Explanation

With linear indexing the elements of an MxN MATLAB matrix get consecutive numbers in a flat 1-dimensional array of length M * N.

In fact returning linear indices is the default mode of operation for MATLAB function

    k = find(X).

As @beaker pointed out in the comments you can just use the output of find(X) as in

   matrix(find(matrix == 0)) = 1.

However if you have already got the vectors of row and column indices also known as subscripts, you could convert them into linear indices using the sub2ind function.

Upvotes: 3

Related Questions