1

I am trying to index my matrix based on two conditions, I'll explain.

Let's say I have two matrices:

a = [7 3 4; 5 6 7; 4 8 0];
b = [1 9 8; 2 4 6; 6 1 6];

And a third matrix to index:

c = [1 2 3; 4 5 6; 7 8 9];

My aim is to index c in a way that I get a 3x3 matrix in which only the values of c are copied over for whose indexes the following conditions are met and the rest are zeros.

a <= 5, b >= 6

Resulting matrix:

result = [0 2 3; 0 0 0; 7 0 9]

I hope I was able to explain my problem.

Nikit Parakh
  • 65
  • 1
  • 7

2 Answers2

1

Given

a = [7 3 4; 5 6 7; 4 8 0];
b = [1 9 8; 2 4 6; 6 1 6];
c = [1 2 3; 4 5 6; 7 8 9];
result = zeros(size(c);

Using logical indexing,

>> d = (a <= 5) & (b >= 6)
d =
  0  1  1
  0  0  0
  1  0  1

>> result(d) = c(d)
result =
   0   2   3
   0   0   0
   7   0   9
beaker
  • 16,331
  • 3
  • 32
  • 49
0

Loop throw rows and columns and set the result.

for row=1:size(a,1)
    for col=1:size(a,2)
          if(a(row,col)> b(row,col))
              result(row,col) = 0
          else
               result(row,col) = c(row,col)
          end  
    end
end
Paolo
  • 21,270
  • 6
  • 38
  • 69
vishnu sandhireddy
  • 1,148
  • 1
  • 7
  • 12