0

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?

Rócherz
  • 3,976
Mark
  • 825
  • You said $B4$, but all that does is return a value. You need to assign it, i.e. $A = B4$. – TrostAft Nov 21 '18 at 20:44
  • Thanks, I changed that but it still is not modifying matrix B – Mark Nov 21 '18 at 20:48
  • Do you mean even if just one entry was positive we multiply whole the matrix by 4 or just do the case with that individual entry? – Mostafa Ayaz Nov 21 '18 at 20:56
  • just the individual entry – Mark Nov 21 '18 at 21:01
  • i modified what I posted originally. I was able to produce a matrix that only added 4 when entries were <0 but for some reason it would not multiply by 4 when entry was >=0 – Mark Nov 21 '18 at 21:05

2 Answers2

0

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

 A=B.*(B>0)*4+(B+6).*(B<0)
Dmitry
  • 1,337
0

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)
Rócherz
  • 3,976