1/X & X^-1 are they the same?

10 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2012-6-18
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.)

请先登录,再进行评论。

采纳的回答

Greg Heath
Greg Heath 2012-6-18
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 个评论
Greg Heath
Greg Heath 2012-6-18
maxabs(invX2-invX1), maxabs(invX3-invX1), maxabs(invX2-invX3)
ans = 2.6645e-014
ans = 2.6645e-014
ans = 0
Greg

请先登录,再进行评论。

更多回答(3 个)

Rui Zhao
Rui Zhao 2012-6-18
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.

Titus Edelhofer
Titus Edelhofer 2012-6-18
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

Jan
Jan 2012-6-18
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;

类别

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