Well,
My first question here.
Is it possible to build an "If" statement using only "max" and "min" statements?
The problem that i have Is that I need to compare 2 numbers (A and B)and see if B > 1.1 x A. If that happens I pick B if not, I pick A .
Any idea?
If your logical operators accept non-boolean value, you could do it as follows:
n = Max(B - 1.1*A, 0)
output = Max(B*(n && n), A)
An if statement, whether in pure (order-invariant) logic or in procedural logic, will work on boolean statements only. That means true or false. A min or max function returns a number, not a true/false value. So the short answer to your question is no, it is not possible to build an if statement using max and min return values.
Now, in the details of your question, you shed a little more light on what you want. What's confusing though is how max and min enters into the equation. B > 1.1*A requires no Max and Min processing, so are you using Max and Min functions to arrive at B and at A? If so, then simply process them first, and then plug them into that equation.
And because "greater than" and "less than" comparions DO return true/false values, you're in luck. Just use that in your "if" statement. Here is some pseudo-code.
max1 = 25
max2 = 72
min1 = 95
min2 = 80
A = Max(max1,max2)
B = Min(min1,min2)
O = NULL
if B > 1.1 * A then
set O = B
else
set O = A
end if
When the output of an if statement is a value, as opposed to a command, as you seem to desire, some languages use the "elvis" operator, which makes things prettier. Using it, you would just write:
O = B > 1.1 * A ? B : A
Related
I have the following:
include("as_mod.jl")
solvetimes = 50:200
timevector = Array{Float64}(undef,length(solvetimes))
for i in solvetimes
global T
T = i
include("as_dat_large.jl")
m, x, z = build_model(true,true)
setsolver(m, GurobiSolver(MIPGap = 2e-2, TimeLimit = 3600))
solve(m)
timevector[i-49] = getsolvetime(m)
end
plot(solvetimes,log.(timevector),
title = "solvetimes vs T", xlabel = "T", ylabel = "log(t)")
And this works great as long as my solvetimes vector is incremented by only 1. However, I'm interested in an 30-increment and it obviously does not work then since my timevector then goes out of bounds. Is there any way of solving this issue? I read about and attempted to use the push! function but to no avail.
I apologize if my question is not good but I don't see how to improve it. The question is essentially about for loops where the index does NOT start at 1 and is only incremented with 1 up to an upper bound, but rather a non-one increment and a start different from 0 or one, if that makes sense.
The : syntax in 50:200 or 50:30:200 creates a range object in Julia. These range objects are not only iterable but also implement the method getindex which means that you can simply access the steps in the range with a[index] syntax as if it is an array.
julia> solvetimes = 50:30:200 # 50, 80, 110, 140, ...
50:30:200
julia> solvetimes[3]
110
You can solve your problem in several ways.
First, you can introduce an itercount variable to count the number of iterations and know at which index of timevector you will put the solve-time.
solvetimes = 50:30:200 # increment by 30
timevector = Vector{Float64}(undef,length(solvetimes))
itercount = 1
for i in solvetimes
...
timevector[itercount] = getsolvetime(m)
global itercount
itercount += 1
end
Other way would be to create an empty timevector and push!.
solvetimes = 50:30:200 # increment by 30
timevector = Float64[] # an empty Float64 vector
for i in solvetimes
...
push!(timevector, getsolvetime(m)) # push the value `getsolvetime(m)` into `timevector`
end
push! operation may require julia to allocate memory and copy data to compensate increasing array size, hence might not be very efficient, although it does not really matter in your problem.
Another way would be to iterate from 1 to length of solvetimes. Your loop control variable is still incremented one-by-one but now it represents the index in solvetimes rather than the time point.
solvetimes = 50:30:200 # increment by 30
len = length(solvetimes)
timevector = Vector{Float64}(undef, len)
for i in 1:len
global T
T = solvetimes[i]
...
timevector[i] = getsolvetime(m)
end
With these modifications, kth value in timevector, timevector[k] stands for the solve-time for solvetime[k].
You might also find other ways to solve the issue, like using Dicts etc.
I would like to know how to overload a function in scilab. It doesn't seem to be as simple as in C++. For example,
function [A1,B1,np1]=pivota_parcial(A,B,n,k,np)
.......//this is just an example// the code doesn't really matter
endfunction
//has less input/output variables//operates differently
function [A1,np1]=pivota_parcial(A,n,k,np)
.......//this is just an example// the code doesn't really matter
endfunction
thanks
Beginner in scilab ....
You can accomplish something like that by combining varargin, varargout and argn() when you implement your function. Take a look at the following example:
function varargout = pivota_parcial(varargin)
[lhs,rhs] = argn();
//first check number of inputs or outputs
//lhs: left-hand side (number of outputs)
//rhs: right-hand side (number of inputs)
if rhs == 4 then
A = varargin(1); B = 0;
n = varargin(2); k = varargin(3);
np = varargin(4);
elseif rhs == 5 then
A = varargin(1); B = varargin(2);
n = varargin(3); k = varargin(4);
np = varargin(5);
else
error("Input error message");
end
//computation goes on and it may depend on (rhs) and (lhs)
//for the sake of running this code, let's just do:
A1 = A;
B1 = B;
np1 = n;
//output
varargout = list(A1,B1,np1);
endfunction
First, you use argn() to check how many arguments are passed to the function. Then, you rename them the way you need, doing A = varargin(1) and so on. Notice that B, which is not an input in the case of 4 inputs, is now set to a constant. Maybe you actually need a value for it anyways, maybe not.
After everything is said and done, you need to set your output, and here comes the part in which using only varargout may not satisfy your need. If you use the last line the way it is, varargout = list(A1,B1,np1), you can actually call the function with 0 and up to 3 outputs, but they will be provided in the same sequence as they appear in the list(), like this:
pivota_parcial(A,B,n,k,np);: will run and the first output A1 will be delivered, but it won't be stored in any variable.
[x] = pivota_parcial(A,B,n,k,np);: x will be A1.
[x,y] = pivota_parcial(A,B,n,k,np);: x will be A1 and y will be B1.
[x,y,z] = pivota_parcial(A,B,n,k,np);: x will be A1, y will be B1, z will be np1.
If you specifically need to change the order of the output, you'll need to do the same thing you did with your inputs: check the number of outputs and use that to define varargout for each case. Basically, you'll have to change the last line by something like the following:
if lhs == 2 then
varargout = list(A1,np1);
elseif lhs == 3 then
varargout = list(A1,B1,np1);
else
error("Output error message");
end
Note that even by doing this, the ability to call this functions with 0 and up to 2 or 3 outputs is retained.
Suppose a function, G, takes two arguments; a and b: G(a = some number, b = some number).
Now two situations (wondering what commands to use in each case?):
1- if a user puts G(b = some number), will the if(missing(a)){do this} recognize the complete absence of a argument? AND more importantly:
2- if a user puts G(a =, b = some number), still will the if(missing(a)){do this} recognize a = but lack of some number in front of it?
Defining the function as below doesn't throw an error in both the cases:
ch <- function(a=NA,b=NA){ if(is.na(a)) return(b) else( return(a+b)) }
> ch(b=2)
[1] 2
> ch(a=,b=2)
[1] 2
How can you get the length of the curve down below between 0 and 4*pi? The commands you should use are inttrap and diff. Here is what I have now:
t=linspace(0,4*%pi)
x=(4+sin(a*t)).*cos(3*t)
y=(4+sin(a*t)).*sin(3*t)
z=cos(3*t)
xx=diff(x)
yy=diff(y)
zz=diff(z)
aid=sqrt(xx^2+yy^2+zz^2)
length=inttrap([t],aid)
Getting error message, the last step is not right.
The reason for error message is that t and aid have different sizes. And that is because diff returns a vector with 1 entry fewer than the input. You can see how it works on an example: diff([3 1 5]) is [-2 4].
To fix this, use t(1:$-1), which omits the last entry of t. That is,
len = inttrap(t(1:$-1), aid)
(Please don't use length, which is a function name in Scilab.)
Another problem you have is that diff is just differences, not a derivative. To get the derivative, you need to divide by the step size, which in your case is t(2)-t(1).
Also, the syntax xx^2 is deprecated for elementwise power; use xx.^2 instead
t = linspace(0,4*%pi)
a = 1
x = (4+sin(a*t)).*cos(3*t)
y = (4+sin(a*t)).*sin(3*t)
z = cos(3*t)
step = t(2)-t(1)
xx = diff(x)/step
xy = diff(y)/step
xz = diff(z)/step
aid = sqrt(xx.^2+yy.^2+zz.^2)
len = inttrap(t(1:$-1), aid)
I want to find the key corresponding to the min or max value of a dictionary in julia. In Python I would to the following:
my_dict = {1:20, 2:10}
min(my_dict, my_dict.get)
Which would return the key 2.
How can I do the same in julia ?
my_dict = Dict(1=>20, 2=>10)
minimum(my_dict)
The latter returns 1=>20 instead of 2=>10 or 2.
You could use reduce like this, which will return the key of the first smallest value in d:
reduce((x, y) -> d[x] ≤ d[y] ? x : y, keys(d))
This only works for non-empty Dicts, though. (But the notion of the “key of the minimal value of no values” does not really make sense, so that case should usually be handled seperately anyway.)
Edit regarding efficiency.
Consider these definitions (none of which handle empty collections)...
m1(d) = reduce((x, y) -> d[x] ≤ d[y] ? x : y, keys(d))
m2(d) = collect(keys(d))[indmin(collect(values(d)))]
function m3(d)
minindex(x, y) = d[x] ≤ d[y] ? x : y
reduce(minindex, keys(d))
end
function m4(d)
minkey, minvalue = next(d, start(d))[1]
for (key, value) in d
if value < minvalue
minkey = key
minvalue = value
end
end
minkey
end
...along with this code:
function benchmark(n)
d = Dict{Int, Int}(1 => 1)
m1(d); m2(d); m3(d); m4(d); m5(d)
while length(d) < n
setindex!(d, rand(-n:n), rand(-n:n))
end
#time m1(d)
#time m2(d)
#time m3(d)
#time m4(d)
end
Calling benchmark(10000000) will print something like this:
1.455388 seconds (30.00 M allocations: 457.748 MB, 4.30% gc time)
0.380472 seconds (6 allocations: 152.588 MB, 0.21% gc time)
0.982006 seconds (10.00 M allocations: 152.581 MB, 0.49% gc time)
0.204604 seconds
From this we can see that m2 (from user3580870's answer) is indeed faster than my original solution m1 by a factor of around 3 to 4, and also uses less memory. This is appearently due to the function call overhead, but also the fact that the λ expression in m1 is not optimized very well. We can alleviate the second problem by defining a helper function like in m3, which is better than m1, but not as good as m2.
However, m2 still allocates O(n) memory, which can be avoided: If you really need the efficiency, you should use an explicit loop like in m4, which allocates almost no memory and is also faster.
another option is:
collect(keys(d))[indmin(collect(values(d)))]
it depends on properties of keys and values iterators which are not guaranteed, but in fact work for Dicts (and are guaranteed for OrderedDicts). like the reduce answer, d must be non-empty.
why mention this, when the reduce, pretty much nails it? it is 3 to 4 times faster (at least on my computer) !
Here is another way to find Min with Key and Value
my_dict = Dict(1 => 20, 2 =>10)
findmin(my_dict) gives the output as below
(10, 2)
to get only key use
findmin(my_dict)[2]
to get only value use
findmin(my_dict)[1]
Hope this helps.
If you only need the minimum value, you can use
minimum(values(my_dict))
If you need the key as well, I don't know a built-in function to do so, but you can easily write it yourself for numeric keys and values:
function find_min_key{K,V}(d::Dict{K,V})
minkey = typemax(K)
minval = typemax(V)
for key in keys(d)
if d[key] < minval
minkey = key
minval = d[key]
end
end
minkey => minval
end
my_dict = Dict(1=>20, 2=>10)
find_min_key(my_dict)
findmax(dict)[2]
findmin(dict)[2]
Should also return the key corresponding to the max and min value(s). Here [2] is the index of the key in the returned tuple.