Johan
Johan

Reputation: 63

Set specified indices to zero

I have two matrices (x1 and x2) with same size. I would like to use the elements equal to zero in x1 to put the sames elements to zero in x2.

The non working solution I've got now follows:

[i j] = find(x1 == 0);
x2(i,j) = 0;

I've also got a working solution which is:

[i j] = find(x1 == 0);
for n=1:length(i)
    x2(i(n),j(n)) = 0;
end

thanks!

Upvotes: 4

Views: 3159

Answers (1)

b3.
b3.

Reputation: 7165

Try x2(x1 == 0) = 0. For example:

>> x1 = rand(5, 5)

x1 =

    0.4229    0.6999    0.5309    0.9686    0.7788
    0.0942    0.6385    0.6544    0.5313    0.4235
    0.5985    0.0336    0.4076    0.3251    0.0908
    0.4709    0.0688    0.8200    0.1056    0.2665
    0.6959    0.3196    0.7184    0.6110    0.1537

>> x2 = randi(2, 5, 5) - 1

x2 =

     0     1     1     0     1
     0     1     0     0     1
     1     1     1     1     0
     0     1     1     1     1
     1     0     0     0     0

>> x1(x2 == 0) = 0

x1 =

         0    0.6999    0.5309         0    0.7788
         0    0.6385         0         0    0.4235
    0.5985    0.0336    0.4076    0.3251         0
         0    0.0688    0.8200    0.1056    0.2665
    0.6959         0         0         0         0

Upvotes: 3

Related Questions