Reputation: 21895
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
Upvotes: 3
Views: 349
Reputation: 8218
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
Upvotes: 2
Reputation: 32930
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.
Upvotes: 2
Reputation: 6887
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.
Upvotes: 2