1/X & X^-1 are they the same?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
i'm about to write something that involves alot of reciprocals.
i want to know is 1/X the same as X^-1?
mathematically its the same, but which does matlab prefers? (that can make it simulate faster)
or are they really the same?
1 Kommentar
Walter Roberson
am 18 Jun. 2012
Is X scalar or matrix?
If X is scalar, you should use the dot operators, ./ and .^
I do not know at the moment which would be faster or more accurate (if either.)
Akzeptierte Antwort
Greg Heath
am 18 Jun. 2012
clear all, clc
ver
% ---------------------------------------------------------------------------
% MATLAB Version 7.13.0.564 (R2011b)
% OperatingSystem: MicrosoftWindows7 Version6.1 (Build7601: ServicePack1)
% Java VM Version: Java 1.6.0_17-b04 with Sun Microsystems Inc.
% Java HotSpot(TM) Client VM mixed mode
% ---------------------------------------------------------------------------
X = randn(100);
for j = 1:5
tic
for i = 1:1e5
invX1 = eye(100)/X;
end
time1(j) = toc % 47.9 46.8 47.3 46.5 46.9
tic
for i = 1:1e5
invX2 = X^(-1);
end
time2(j) = toc % 62.6 62.8 62.6 61.9 62.3
for i = 1:1e5
invX3 = inv(X);
end
time3(j) = toc % 98.7 96.3 96.5 97.8 97.2
end
Hope this helps.
Greg
1 Kommentar
Greg Heath
am 18 Jun. 2012
maxabs(invX2-invX1), maxabs(invX3-invX1), maxabs(invX2-invX3)
ans = 2.6645e-014
ans = 2.6645e-014
ans = 0
Greg
Weitere Antworten (3)
Rui Zhao
am 18 Jun. 2012
If X is a square matrix, 1/X shall be inv(X) since Matlab can't recognize 1/X for a matrix. Moreover, inv(X) is just the same for a square matrix as X^(-1).
For large matrix, the function inv() is well optimized by matlab and it costs less time than X^(-1). While for small matrix, their computational costs are comparable.
0 Kommentare
Titus Edelhofer
am 18 Jun. 2012
Hi Raymond,
if it's scalars take Walter's advice on ./ and .^ (should be no measurable difference between those). If X is a matrix, it depends, what you need the reziprocals for. For solving linear equations? In this case / (and \) are much preferable to ^(-1): / and \ solve linear systems, ^(-1) computes the inverse (which is a way to solve linear equations but a bad (unstable) one).
Titus
0 Kommentare
Jan
am 18 Jun. 2012
The division is faster than the power operator. If you are in doubt, test it:
x = rand(1, 1e6);
tic;
for i = 1:length(x)
x(i) = 1 / x(i);
end
toc;
tic;
for i = 1:length(x)
x(i) = x(i) ^ -1;
end
toc;
Of course it would be faster to process the complete array at once in this example:
tic;
x = 1 ./ x;
toc;
tic;
x = x .^ -1;
toc;
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!