Trying to avoid for cycles

2 次查看(过去 30 天)
Riccardo Sorvillo
Riccardo Sorvillo 2019-10-26
Hello world!
I have to obtain a matrix T starting from a matrix A and a vector w. Specifically:
  • matrix A is a reciprocal (i.e. A(i,j) = 1/A(j,i)) square matrix of dimension N composed by all positive elements between 0 and 9;
  • w is a column vector of dimension N whose entries are between 0 and 1.
T is defined element-wise as T(i,j) = A(i,j)*w(i)/w(j), so it is still a square matrix of dimension n. I used two ways: a double for cycle and element-wise moltiplications. Before going for the element-wise operations, I tested if the two methods provide the same result using logical operations (T==T2), and it happened to be incorrect. An example follows. It occurs that matrices T and T2 are not completely identical (some elements in the logical variables ans are zeros), eventhough if I open T and T2 from workspace or display the critical elements in command window the two seem identical.
I'd say that the problem depends on the well-known problems of matlab with decimal digits, and most probably the bias is negligible, but here's where my doubt emerges: which one of the two is more correct (assuming that both are correct)?
A = [1 2 3 1 3 8;
1/2 1 7 3 1/5 1;
1/3 1/7 1 1/5 1/5 1/2;
1 1/3 5 1 1 1/3;
1/3 5 5 1 1 3;
1/8 1 2 3 1/3 1];
n = size(A,1);
[w, lambda] = eig(A);
[Lmax, indL] = max(diag(lambda));
w = w(:,indL)/(sum(w(:,indL)));
T = A.*(w'./w);
T2 = zeros(size(A));
for i = 1:n
for j = 1:n
T2(i,j) = A(i,j)*w(j)/w(i);
end
end
T == T2
Thank you in advance,
Riccardo
  4 个评论
Riccardo Sorvillo
Riccardo Sorvillo 2019-10-27
Firstly, thank you both for the answers.
"The "problem" has nothing whatever to do with MATLAB, it's totally the result of IEEE floating point precision."
I didn't know that, I thought it was a problem of MATLAB only, my mistake.
Then, thank you Fabio Freschi for let me noticing the very silly mistake in the double for cycle.
I appreciated your helps.
Bjorn Gustavsson
Bjorn Gustavsson 2019-10-27
That is not really a "mistake" in the general sense - only here for exact comparison between two construction-methods is it a "mistake". The general lesson to learn is that you have to "accept" floating-point accuracy limitations - even your algorithms should be stable to such small numerical errors.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by