Use varargin for multiple arguments with default values in MATLAB - function

Is there a way to supply arguments using varargin in MATLAB in the following manner?
Function
func myFunc(varargin)
if a not given as argument
a = 2;
if b not given as argument
b = 2;
if c not given as argument
c = a+b;
d = 2*c;
end
I want to call the above function once with b = 3 and another time while the previous one is running in the same command window with a = 3 and c = 3 and letting b take the default value in the function this time. How can it be done using varargin?

Here's the latest and greatest way to write the function (using arguments blocks from R2019b)
function out = someFcn(options)
arguments
options.A = 3;
options.B = 7;
options.C = [];
end
if isempty(options.C)
options.C = options.A + options.B;
end
out = options.A + options.B + options.C;
end
Note that this syntax does not allow you to say options.C = options.A + options.B directly in the arguments block.
In MATLAB < R2021a, you call this like so
someFcn('A', 3)
In MATLAB >= R2021a, you can use the new name=value syntax
someFcn(B = 7)

Here are two ways to do this which have been available since 2007a (i.e. a long time!). For a much newer approach, see Edric's answer.
Use nargin and ensure your inputs are always in order
Use name-value pairs and an input parser
nargin: slightly simpler but relies on consistent input order
function myFunc( a, b, c )
if nargin < 1 || isempty(a)
a = 2;
end
if nargin < 2 || isempty(b)
b = 2;
end
if nargin < 3 || isempty(c)
c = a + b;
end
end
Using the isempty check you can optionally provide just later arguments, for example myFunc( [], 4 ) would just set b=4 and use the defaults otherwise.
inputParser: more flexible but can't directly handle the c=a+b default
function myFunc( varargin )
p = inputParser;
p.addOptional( 'a', 2 );
p.addOptional( 'b', 2 );
p.addOptional( 'c', NaN ); % Can't default to a+b, default to NaN
p.parse( varargin{:} );
a = p.Results.a;
b = p.Results.b;
c = p.Results.c;
if isnan(c) % Handle the defaulted case
c = a + b;
end
end
This would get used like myFunc( 'b', 4 );. This approach is also agnostic to the input order because of the name-value pairs, so you can also do something like myFunc( 'c', 3, 'a', 1 );

Related

Function with vector as argument in Octave

How can I make a function with a vector as input and a matrix as an output?
I have to write a function that will convert cubic meters to liters and English gallons. The input should be a vector containing volume values ​​in m ^ 3 to be converted. The result should be a matrix in which the first column contains the result in m ^ 3, the second liter, the third English gallon.
I tried this:
function [liter, gallon] = function1 (x=[a, b, c, d]);
liter= a-10+d-c;
gallon= b+15+c;
endfunction
You're almost there.
The x=[a,b,c,d] part is superfluous, your argument should be just x.
function [liter, gallon] = function1 (x);
a = x(1); b = x(2); c = x(3); d = x(4);
liter = a - 10 + d - c;
gallon = b + 15 + c;
endfunction
If you want your code to be safe and guard against improper inputs, you can perform such checks manually inside the function, e.g.
assert( nargin < 1 || nargin > 4, "Wrong number of inputs supplied");
The syntax x=[a,b,c,d] does not apply to octave; this is reserved for setting up default arguments, in which case a, b, c, and d should be given specific values that you'd want as the defaults. if you had said something like x = [1,2,3,4], then this would be fine, and it would mean that if you called the function without an argument, it would set x up to this default value.

How to dynamically generate functions in Lua?

If I have a table {field1=1,field2=0} (0: ascending order, 1: descending order)
I want to get a function:
function(x,y)
return x.field1 < y.field1 --there 0:'<',1:'>='
end
field1 in the table and the sorting rule can be injected in the function.
How to generate this code dynamically?
Let's talk about more than just the code generation approach! As in the question, consider the need of a function:
function (x, y)
return x.field1 --[[ < or >= ]] y.field1
end
For the sake of the examples assume that we have global variables:
FIRST = {field1 = 3}
SECOND = {field1 = 5}
Branching
The simplest solution (perhaps also the most typical?) that comes to my mind is a verbose if:
function foo (x, y, o)
if o == nil or o == "asc" then
return x.field1 < y.field1
end
if o == "dsc" then
return x.field1 >= y.field1
end
error("Unknown option")
end
-- Example:
foo(FIRST, SECOND, "asc")
foo(FIRST, SECOND, "dsc")
Note that early returns make else unnecessary in this case but it might not always be true.
Anonymous function
But, hey, what's that? What if rather than a string option we pass something more bizarre like... something that can be called? Let's go with a simple function this time:
local asc = function (a, b) return a < b end
local dsc = function (a, b) return a >= b end
function bar (x, y, compare)
compare = compare or asc
return compare(x.field1, y.field1)
end
-- Example:
bar(FIRST, SECOND, asc)
bar(FIRST, SECOND, dsc)
bar(FIRST, SECOND, function (a, b) return a < b end)
Higher-order function
The previous example doesn't really look that good with a such simple operation, but let's take it as a base and let's create a function that will return us the desired function:
function make (compare)
return function (x, y) return compare(x.field1, y.field1) end
end
-- Example:
local asc = make(function (a, b) return a < b end)
local dsc = make(function (a, b) return a >= b end)
asc(FIRST, SECOND)
dsc(FIRST, SECOND)
Actual generation
Now then, let's try something closer to code generation. Lua gives us the ability to load chunks as we go with load* function family.
Please note that load in 5.1 is different from load in 5.2 or load in 5.3. In 5.1 you want to use loadstring instead of load.
function generate (op)
return load(string.format("return function (x, y) return x.field1 %s y.field1 end", op))()
end
-- Example:
local asc = generate("<")
local dsc = generate(">=")
asc(FIRST, SECOND)
dsc(FIRST, SECOND)

Octave call a function as a variable of another function

I wrote a bisection method in Octave but it can't consume another function..
My bisection method code is like:
function[x,b] = bisection(f,a,b)
t = 10e-8
while abs(b-a) > t;
c = (a+b)/2;
if f(a) * f(b) <= 0
a = a;
b = c;
else
b = b;
a = c
endif
endwhile
x = (a+b)/2
endfunction
And I already have a file f1.m:
function y = f1(x)
y = x^2 - 4;
endfunction
But when I call [x,v] = bisection[f1,0,5], I get:
>> [t,v] = bisection(f1,0,5)
error: 'x' undefined near line 2 column 5
error: called from
f1 at line 2 column 3
error: evaluating argument list element number 1
what you want is to pass a pointer to f1 to your function bisection so the right call would be
[t,v] = bisection(#f1,0,5)
which outputs:
t = 1.0000e-07
a = 0.62500
a = 0.93750
a = 1.0938
a = 1.1719
a = 1.2109
a = 1.2305
a = 1.2402
a = 1.2451
a = 1.2476
a = 1.2488
a = 1.2494
a = 1.2497
a = 1.2498
a = 1.2499
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
a = 1.2500
x = 1.2500
t = 1.2500
v = 1.2500
Andy has given you the answer on how to fix this. I would just like to add why you get that error and what it means. Consider the following octave session:
octave:1> function Out = g1(x); Out = x+5; end
octave:2> function Out = g2(); Out = 10;end
octave:3>
octave:3> g2
ans = 10
octave:4> g1
error: 'x' undefined near line 1 column 29
error: called from
g1 at line 1 column 27
I.e., when you write g1 or g2 here, this is an actual function call. The call to g2 succeeds because g2 does not take any arguments; the syntax g2 is essentially equivalent to g2(). However, the call to g1 fails, because g1 expects an argument, and we didn't provide one.
Compare with:
octave:4> a = #g1;
octave:5> b = #g2;
octave:6> a
a = #g1
octave:7> a(1)
ans = 6
octave:8> b
b = #g2
octave:9> b()
ans = 10
where you have created handles to these functions, which you can capture into variables, and pass them as arguments into functions. These handles could then be called as a(5) or b() inside the function that received them as arguments, and it would be like calling the original g1 and g2 functions.
When you called bisection(f1,0,5), you essentially called bisection(f1(),0,5), i.e. you asked octave to evaluate the function f1 without passing any arguments, and use the result as the first input argument to the bisection function. Since function f1 is defined to take an input argument and you didn't supply any, octave complains that when it tries to evaluate y = x^2 - 4; as per the definition of f1, x was not passed as an input argument and was therefore undefined.
Therefore, to pass a "function" as an arbitrary argument that can be called inside your bisection function, you need to pass a function handle instead, which can be created using the #f1 syntax. Read up on "anonymous functions" on the octave (or matlab) documentation.

MIPS Programming instruction count issue

I wrote this mips code to find the gcf but I am confused on getting the number of instructions executed for this code. I need to find a linear function as a function of number of times the remainder must be calculated before an answer. i tried running this code using Single step with Qtspim but not sure on how to proceed.
gcf:
addiu $sp,$sp,-4 # adjust the stack for an item
sw $ra,0($sp) # save return address
rem $t4,$a0,$a1 # r = a % b
beq $t4,$zero,L1 # if(r==0) go to L1
add $a0,$zero,$a1 # a = b
add $a1,$zero,$t4 # b = r
jr gcf
L1:
add $v0,$zero,$a1 # return b
addiu $sp,$sp,4 # pop 2 items
jr $ra # return to caller
There is absolutely nothing new to show here, the algorithm you just implemented is the Euclidean algorithm and it is well known in the literature1.
I will nonetheless write an informal analysis here as link only questions are evil.
First lets rewrite the code in an high level formulation:
unsigned int gcd(unsigned int a, unsigned int b)
{
if (a % b == 0)
return b;
return gcd(b, a % b);
}
The choice of unsigned int vs int was dicated by the MIPS ISA that makes rem undefined for negative operands.
Out goal is to find a function T(a, b) that gives the number of step the algorithm requires to compute the GDC of a and b.
Since a direct approach leads to nothing, we try by inverting the problem.
What pairs (a, b) makes T(a, b) = 1, in other words what pairs make gcd(a, b) terminates in one step?
We clearly must have that a % b = 0, which means that a must be a multiple of b.
There are actually an (countable) infinite number of pairs, we can limit our selves to pairs with the smallest, a and b2.
To recap, to have T(a, b) = 1 we need a = nb and we pick the pair (a, b) = (1, 1).
Now, given a pair (c, d) that requires N steps, how do we find a new pair (a, b) such that T(a, b) = T(c, d) + 1?
Since gcd(a, b) must take one step further then gcd(c, d) and since starting from gcd(a, b) the next step is gcd(b, a % b) we must have:
c = b => b = c
d = a % b => d = a % c => a = c + d
The step d = a % c => a = c + d comes from the minimality of a, we need the smallest a that when divided by c gives d, so we can take a = c + d since (c + d) % c = c % c d % c = 0 + d = d.
For d % c = d to be true we need that d < c.
Our base pair was (1, 1) which doesn't satisfy this hypothesis, luckily we can take (2, 1) as the base pair (convince your self that T(2, 1) = 1).
Then we have:
gcd(3, 2) = gcd(2, 1) = 1
T(3, 2) = 1 + T(2, 1) = 1 + 1 = 2
gcd(5, 3) = gcd(3, 2) = 1
T(5, 3) = 1 + T(3, 2) = 1 + 2 = 3
gcd(8, 5) = gcd(5, 3) = 1
T(8, 5) = 1 + T(5, 3) = 1 + 3 = 4
...
If we look at the pair (2, 1), (3, 2), (5, 3), (8, 5), ... we see that the n-th pair (starting from 1) is made by the number (Fn+1, Fn).
Where Fn is the n-th Fibonacci number.
We than have:
T(Fn+1, Fn) = n
Regarding Fibonacci number we know that Fn ∝ φn.
We are now going to use all the trickery of asymptotic analysis, particularly in the limit of the big-O notation considering φn or φn + 1 is the same.
Also we won't use the big-O symbol explicitly, we rather assume that each equality is true in the limit. This is an abuse, but makes the analysis more compact.
We can assume without loss of generality that N is an upper bound for both number in the pair and that it is proportional to φn.
We have N ∝ φn that gives logφ N = n, this ca be rewritten as log(N)/log(φ) = n (where logs are in base 10 and log(φ) can be taken to be 1/5).
Thus we finally have 5logN = n or written in reverse order
n = 5 logN
Where n is the number of step taken by gcd(a, b) where 0 < b < a < N.
We can further show that if a = ng and b = mg with n, m coprimes, than T(a, b) = T(n, m) thus the restriction of taking the minimal pairs is not bounding.
1 In the eventuality that you rediscovered such algorithm, I strongly advice against continue with reading this answer. You surely have a sharp mind that would benefit the most from a challenge than from an answer.
2 We'll later see that this won't give rise to a loss of generality.

Finding closest match in collection of numbers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 8 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
So I got asked today what was the best way to find the closes match within a collection.
For example, you've got an array like this:
1, 3, 8, 10, 13, ...
What number is closest to 4?
Collection is numerical, unordered and can be anything. Same with the number to match.
Lets see what we can come up with, from the various languages of choice.
11 bytes in J:
C=:0{]/:|#-
Examples:
>> a =: 1 3 8 10 13
>> 4 C a
3
>> 11 C a
10
>> 12 C a
13
my breakdown for the layman:
0{ First element of
] the right argument
/: sorted by
| absolute value
# of
- subtraction
Shorter Python: 41 chars
f=lambda a,l:min(l,key=lambda x:abs(x-a))
My attempt in python:
def closest(target, collection) :
return min((abs(target - i), i) for i in collection)[1]
Groovy 28B
f={a,n->a.min{(it-n).abs()}}
Some C# Linq ones... too many ways to do this!
decimal[] nums = { 1, 3, 8, 12 };
decimal target = 4;
var close1 = (from n in nums orderby Math.Abs(n-target) select n).First();
var close2 = nums.OrderBy(n => Math.Abs(n - target)).First();
Console.WriteLine("{0} and {1}", close1, close2);
Even more ways if you use a list instead, since plain ol arrays have no .Sort()
Assuming that the values start in a table called T with a column called N, and we are looking for the value 4 then in Oracle SQL it takes 59 characters:
select*from(select*from t order by abs(n-4))where rownum=1
I've used select * to reduce the whitespace requirements.
Because I actually needed to do this, here is my PHP
$match = 33;
$set = array(1,2,3,5,8,13,21,34,55,89,144,233,377,610);
foreach ($set as $fib)
{
$diff[$fib] = (int) abs($match - $fib);
}
$fibs = array_flip($diff);
$closest = $fibs[min($diff)];
echo $closest;
PostgreSQL:
select n from tbl order by abs(4 - n) limit 1
In the case where two records share the same value for "abs(4 - id)" the output would be in-determinant and perhaps not a constant. To fix that I suggest something like the untested guess:
select n from tbl order by abs(4 - n) + 0.5 * 4 > n limit 1;
This solution provides performance on the order of O(N log N), where O(log N) is possible for example: https://stackoverflow.com/a/8900318/1153319
Ruby like Python has a min method for Enumerable so you don't need to do a sort.
def c(value, t_array)
t_array.min{|a,b| (value-a).abs <=> (value-b).abs }
end
ar = [1, 3, 8, 10, 13]
t = 4
c(t, ar) = 3
Language: C, Char count: 79
c(int v,int*a,int A){int n=*a;for(;--A;++a)n=abs(v-*a)<abs(v-n)?*a:n;return n;}
Signature:
int closest(int value, int *array, int array_size);
Usage:
main()
{
int a[5] = {1, 3, 8, 10, 13};
printf("%d\n", c(4, a, 5));
}
Scala (62 chars), based on the idea of the J and Ruby solutions:
def c(l:List[Int],n:Int)=l.sort((a,b)=>(a-n).abs<(b-n).abs)(0)
Usage:
println(c(List(1,3,8,10,13),4))
PostgreSQL:
This was pointed out by RhodiumToad on FreeNode and has performance on the order of O(log N)., much better then the other PostgreSQL answer here.
select * from ((select * from tbl where id <= 4
order by id desc limit 1) union
(select * from tbl where id >= 4
order by id limit 1)) s order by abs(4 - id) limit 1;
Both of the conditionals should be "or equal to" for much better handling of the id exists case. This also has handling in the case where two records share the same value for "abs(4 - id)" then that other PostgreSQL answer here.
The above code doesn't works for floating numbers.
So here's my revised php code for that.
function find_closest($match, $set=array()) {
foreach ($set as $fib) {
$diff[$fib] = abs($match - $fib);
}
return array_search(min($diff), $diff);
}
$set = array('2.3', '3.4', '3.56', '4.05', '5.5', '5.67');
echo find_closest(3.85, $set); //return 4.05
Python by me and https://stackoverflow.com/users/29253/igorgue based on some of the other answers here. Only 34 characters:
min([(abs(t-x), x) for x in a])[1]
Haskell entry (tested):
import Data.List
near4 = head . sortBy (\n1 n2 -> abs (n1-4) `compare` abs (n2-4))
Sorts the list by putting numbers closer to 4 near the the front. head takes the first element (closest to 4).
Ruby
def c(r,t)
r.sort{|a,b|(a-t).abs<=>(b-t).abs}[0]
end
Not the most efficient method, but pretty short.
returns only one number:
var arr = new int[] { 1, 3, 8, 10, 13 };
int numToMatch = 4;
Console.WriteLine("{0}",
arr.OrderBy(n => Math.Abs(numToMatch - n)).ElementAt(0));
returns only one number:
var arr = new int[] { 1, 3, 8, 10, 13 };
int numToMatch = 4;
Console.WriteLine("{0}",
arr.Select(n => new{n, diff = Math.Abs(numToMatch - n) }).OrderBy(x => x.diff).ElementAt(0).n);
Perl -- 66 chars:
perl -e 'for(qw/1 3 8 10 13/){$d=($_-4)**2; $c=$_ if not $x or $d<$x;$x=$d;}print $c;'
EDITED = in the for loop
int Closest(int val, int[] arr)
{
int index = 0;
for (int i = 0; i < arr.Length; i++)
if (Math.Abs(arr[i] - val) < Math.Abs(arr[index] - val))
index = i;
return arr[index];
}
Here's another Haskell answer:
import Control.Arrow
near4 = snd . minimum . map (abs . subtract 4 &&& id)
Haskell, 60 characters -
f a=head.Data.List.sortBy(compare`Data.Function.on`abs.(a-))
Kdb+, 23B:
C:{x first iasc abs x-}
Usage:
q)a:10?20
q)a
12 8 10 1 9 11 5 6 1 5
q)C[a]4
5
Python, not sure how to format code, and not sure if code will run as is, but it's logic should work, and there maybe builtins that do it anyways...
list = [1,4,10,20]
num = 7
for lower in list:
if lower <= num:
lowest = lower #closest lowest number
for higher in list:
if higher >= num:
highest = higher #closest highest number
if highest - num > num - lowest: # compares the differences
closer_num = highest
else:
closer_num = lowest
In Java Use a Navigable Map
NavigableMap <Integer, Integer>navMap = new ConcurrentSkipListMap<Integer, Integer>();
navMap.put(15000, 3);
navMap.put(8000, 1);
navMap.put(12000, 2);
System.out.println("Entry <= 12500:"+navMap.floorEntry(12500).getKey());
System.out.println("Entry <= 12000:"+navMap.floorEntry(12000).getKey());
System.out.println("Entry > 12000:"+navMap.higherEntry(12000).getKey());
int numberToMatch = 4;
var closestMatches = new List<int>();
closestMatches.Add(arr[0]); // closest tentatively
int closestDifference = Math.Abs(numberToMatch - arr[0]);
for(int i = 1; i < arr.Length; i++)
{
int difference = Math.Abs(numberToMatch - arr[i]);
if (difference < closestDifference)
{
closestMatches.Clear();
closestMatches.Add(arr[i]);
closestDifference = difference;
}
else if (difference == closestDifference)
{
closestMatches.Add(arr[i]);
}
}
Console.WriteLine("Closest Matches");
foreach(int x in closestMatches) Console.WriteLine("{0}", x);
Some of you don't seem to be reading that the list is unordered (although with the example as it is I can understand your confusion). In Java:
public int closest(int needle, int haystack[]) { // yes i've been doing PHP lately
assert haystack != null;
assert haystack.length; > 0;
int ret = haystack[0];
int diff = Math.abs(ret - needle);
for (int i=1; i<haystack.length; i++) {
if (ret != haystack[i]) {
int newdiff = Math.abs(haystack[i] - needle);
if (newdiff < diff) {
ret = haystack[i];
diff = newdiff;
}
}
}
return ret;
}
Not exactly terse but hey its Java.
Common Lisp using iterate library.
(defun closest-match (list n)
(iter (for i in list)
(finding i minimizing (abs (- i n)))
41 characters in F#:
let C x = Seq.min_by (fun n -> abs(n-x))
as in
#light
let l = [1;3;8;10;13]
let C x = Seq.min_by (fun n -> abs(n-x))
printfn "%d" (C 4 l) // 3
printfn "%d" (C 11 l) // 10
printfn "%d" (C 12 l) // 13
Ruby. One pass-through. Handles negative numbers nicely. Perhaps not very short, but certainly pretty.
class Array
def closest int
diff = int-self[0]; best = self[0]
each {|i|
if (int-i).abs < diff.abs
best = i; diff = int-i
end
}
best
end
end
puts [1,3,8,10,13].closest 4