How to swap values of two variables?

359 次查看(过去 30 天)
For instance, if i ask the user to input the values of a and b, in this case they choose a=10 and b=5 how would I be able to switch them so that it'll be a=5 and b=10.
  4 个评论
Jan
Jan 2021-10-19
编辑:Jan 2021-10-19
@Subhashini Neelamegam: Yes, but this is more efficient:
function [b, a] = swap(a, b)
end

请先登录,再进行评论。

采纳的回答

David Goodmanson
David Goodmanson 2017-10-23
Hi Daniel,
Take a look at the 'deal' command, in this case [b a] = deal(a,b)

更多回答(3 个)

Jan
Jan 2017-10-23
Cheaper than deal:
function [b, a] = swap(a, b)
% This function has no body!
  13 个评论
Rik
Rik 2023-8-29
You generally need to warm up function calls if you want to test timings online. This should be reasonably stable. As you can see, they differ by a lot, but in the other direction than your post shows. Using a function instead of a script might also affect the timings (as you can see, the same code runs over 10x faster inside a function).
timeit(@test_deal);timeit(@test_swap);% warm-up round
timeit(@test_deal),timeit(@test_swap)
ans = 0.0798
ans = 0.0017
function test_deal
c1 = zeros(100);
c2 = ones(100);
for i = 1:100000
[c1,c2] = deal(c2,c1);
end
end
function test_swap
c1 = zeros(100);
c2 = ones(100);
for i = 1:100000
[c1,c2] = swap(c2,c1);
end
end
function [a,b] = swap(a,b)
end
lala
lala 2023-8-29
@Rik Thanks for your reply. You are right. :)

请先登录,再进行评论。


Daniel Afriyie
Daniel Afriyie 2019-10-13
[b, a] = deal(a,b)

AAMIR SHEIKH
AAMIR SHEIKH 2020-8-11
Going Traditionally !!!
a = input("enter a :::");
b = input("enter b :::");
temp = a;
a = b;
b = temp;
[a b]

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by