3

I'm trying to do my best and not use loops in Matlab, but I find it very hard sometimes .

For example I wrote this code :

vector = zeros(p,1);

diagDominantFlag = 1;
for row = 1:p
    for col = 1:q
        if(row ~= col)
            vector(row) = vector(row) + A(row,col);
        end
    end
    if(A(row,row) <= vector(row))
        diagDominantFlag = 0;
        break;
    end
end

Is it possible to vectorize that double for loop?

Thanks

1
  • 2
    I've edited the question, since "breaking" a loop means something totally different to "vectorizing" it. Commented May 30, 2012 at 17:18

3 Answers 3

2

Not an answer to your direct question, but, here's a loopless test for diagonal dominance (since you seem interested in that):

all(diag(A) >= (sum(abs(A),2)-abs(diag(A)) )

or for strict diagonal dominance:

all(diag(A) > (sum(abs(A),2)-abs(diag(A)) )

Also, in your above code, make sure you do abs() on the off-diagonal values.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the abs() observation. Nevertheless, I'll stick to the OP's original code in my answer...
@EitanT I originally thought the same, but I've never seen a definition of diagonal dominance that didn't want the abs()
2

Adding to Ansari's answer, the diagDominantFlag can be calculated by:

diagDominantFlag = all(diag(A) >= (sum(A, 2) - diag(A)));

Thus replacing your double for loop with a one-liner.

1 Comment

Okay,this is really nice.I'll try to remove all the loops from my code.
2

You can replace the inner loop with

vector(row) = sum(A(row, :)) - A(row, row);

and in fact you can replace the whole thing by

vector = sum(A, 2) - diag(A);

To add the check you have in the outer loop, you can then do something like

f = find(diag(A) <= vector);
if length(f) > 0
    diagDominantFlag = 0;
    vector(f(1):end) = 0;
end

6 Comments

+1 for the calculation of vector. The inner loop can be replaced by a vectorized comparsion, though...
Which inner loop? In the OPs question? That loop fills in the vector variable, so I don't see how a comparison would replace that .. can you elaborate?
Sorry for the misunderstanding. I meant to say that the whole ordeal can be replaced by one logical vectorized comparison. Note that the flag retains the value of 1 only if each element in the diagonal is greater or equal to the corresponding element in vector. It's called diagonal dominance.
@Ansari: Can I use abs somewhere here ? since I need to take the absolute value and the rest of the elements of each line , and compare the sum of the absolute value of them with a_ii . Thanks .
vector(row) = sum(abs(A(row, :))) - abs(A(row, row));
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.