How to swap values of two variables?

357 Ansichten (letzte 30 Tage)
Daniel Contreras
Daniel Contreras am 23 Okt. 2017
Kommentiert: lala am 29 Aug. 2023
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 Kommentare
Subhashini Neelamegam
Subhashini Neelamegam am 18 Okt. 2021
This code works
Jan
Jan am 19 Okt. 2021
Bearbeitet: Jan am 19 Okt. 2021
@Subhashini Neelamegam: Yes, but this is more efficient:
function [b, a] = swap(a, b)
end

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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

Weitere Antworten (3)

Jan
Jan am 23 Okt. 2017
Cheaper than deal:
function [b, a] = swap(a, b)
% This function has no body!
  13 Kommentare
Rik
Rik am 29 Aug. 2023
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 am 29 Aug. 2023
@Rik Thanks for your reply. You are right. :)

Melden Sie sich an, um zu kommentieren.


Daniel Afriyie
Daniel Afriyie am 13 Okt. 2019
[b, a] = deal(a,b)
  1 Kommentar
Jan
Jan am 4 Nov. 2019
This was mentioned 2 years ago already.

Melden Sie sich an, um zu kommentieren.


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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by