How can I compare the entry of two matrices?

245 Views Asked by At

Suppose I have two matrix A and B, both are m$\times$n size, now I set a condition: if the entry in A is smaller than a value, I want the entries in same position of B outputted.

For example:

$A=\begin{bmatrix}1&2&3\\4&5&6\\7&8&9 \end{bmatrix}$ and $B=\begin{bmatrix}10&0&1\\3&2&9\\1&0&-6 \end{bmatrix}$

The condition is when the entry in A < 5, and the output result should be:

$B'=\begin{bmatrix}10&0&1\\3&0&0\\0&0&0 \end{bmatrix}$

How can I code MatLab to realize this? Is there any function or package that I can use? Thanks!

3

There are 3 best solutions below

0
On

My license for Matlab expired a few weeks ago however I downloaded octave

$A=\begin{bmatrix}1&2&3\\4&5&6\\7&8&9 \end{bmatrix}$ and $B=\begin{bmatrix}10&0&1\\3&2&9\\1&0&-6 \end{bmatrix}$

$$ B_{ij} =\begin{align}\begin{cases} b_{ij} & \textrm{ if } A_{ij} < 5 \\ \\ 0 & \textrm{ for everywhere else } \end{cases} \end{align}$$

function Bprime =  gen_matrix(A,B,c)
    [m,n] = size(A)
    Bprime = zeros(m,n)
    for i=1:m
      for j=1:n
         my_entry1 = A(i,j)
         my_entry2 = B(i,j)
         if my_entry1 < c
           Bprime(i,j) = my_entry2
          else
           Bprime(i,j) = 0
         endif
      endfor

    endfor

endfunction
0
On

First Idea:

$A<5$ in matlab gives a logical array, or a matrix with $1’s$ where the elements are smaller than $5$ and $0’s$ elsewhere. Simply combine this with element wise multiplication. Note: B’ is not a valid variable name.

function B_out=myfun(A,B,c)
B_out=(A<c) .*B;

Second Idea:

As before create a function where you input matrix $A$ and matrix $B$, as well as a number $c$, and output B_out


For speed, initialize your output B_out to be a matrix of zeros of the right size (the size of A).


Next, note that in matlab $A(1)$ represents the first element (in the upper left hand corner) of a matrix. Going down the first column we have $A(2)$, then $A(3)$, etc, until we finish that column and get to the next one. We want the go through all m*n elements of $A$ and check if it’s less than $c$. In matlab, size(A,1) gives the number of rows of A, and size(A,2) gives the number of columns.


If the element of $A$ is less than $c$, define the corresponding element of the output B_out as the corresponding element of $B$.


function B_out=myfun(A,B,c)

    B_out=zeros(size(A));
    for i=1:size(A,1)*size(A,2)
           if A(i)< c
               B_out(i)=B(i);
           end
    end
1
On
C = zeros (size(B));

fnd = find(A<5);

C(fnd)=B(fnd);