Modifying entries of a matrix selectively

38 Views Asked by At

In my linear algebra class we have a small component of learning Matlab with the occasional assignment.

The question asked to modify an existing (not shown) $25 \times 25$ matrix with the following conditions:

  1. if an entry in the matrix $B$ is $\geq 0$ then multiply by $4$
  2. if an entry in the matrix $B$ is $<0$ then add $6$ to it

I created a function file in Matlab by doing the following:

function [A] = modify_matrix(B, n, m),
    A = zeros(n,m); 
    for i = 1:n, 
        for j = 1:m, 
            if B >= 0, 
                A = B*4; 
            else,
                A = B+6; 
                A(i,j) = B(i,j); 
            end 
        end 
    end
end

This simply reproduces the same matrix $B$.

Any suggestions?

2

There are 2 best solutions below

0
On

Using Matlab vectorization tricks you can do that in one line:

 A=B.*(B>0)*4+(B+6).*(B<0)
0
On

This is what your if-else is missing in your code:

if B(i,j) >= 0, 
    A(i,j) = 4*B(i,j); 
else,
    A(i,j) = 6+B(i,j); 
end

Those (i,j) are what enables you to access/modify an entry.

However, as Dmitry pointed out, Matlab enables us to operate over matrices directly (I'm proposing my own variation of Dmitry's one-liner):

A = 4*B.*(aux = (B>=0)) +(B+6).*(1-aux)