How to perform a conditional assignment on each element of the vector - function

I have a function like this:
y=-2 with x<=0
y=-2+3x^2 with 0=1
I need to compute this function on each element of the 1D matrix, without using a loop.
I thought it was possibile defining a function like this one:
function y= foo(x)
if x<=0
y=-2;
elseif x>=1
y=1;
else
y= -2+3*x.^2;
end
end
But this just produces a single result, how to operate on all elements? I know the . operator, but how to access the single element inside an if?

function b = helper(s)
if s<=0
b=-2;
elseif s>=1
b=1;
else
b= -2+3*s^2;
end
end
Then simply call
arrayfun(#helper, x)
to produce the behaviour you want of your function foo.

Another approach which doesn't need arrayfun() would be to multiply by the conditions:
y = -2*(x <= 0) + (-2+3*x.^2).*(x < 1).*(x > 0) + (x >= 1)
which you could also make a function. This will accept vector inputs for x e.g.
x = [1 4 0 -1 0.5];
y = -2*(x <= 0) + (-2+3*x.^2).*(x < 1).*(x > 0) + (x >= 1)
outputs
y =
1.0000 1.0000 -2.0000 -2.0000 -1.2500

Related

Matlab - Undefined function 'int_f_1' for input arguments of type 'double'

Currently, I am working on a program that integrates x + x^2 + e^x + 2cos(x/2) - 1 with three input variables, a, b, and n. What I need returned is the numerical integral from a to b with n increments. The function also has to return trapezoids for each n as a column vector. Thus, the integral value as a scalar, and a vector of values.
I've gotten to a point where the function int_f_1 is undefined for some reason, and I have no idea why. I thought by nesting that function under the test function, it would help. But it does not, and I don't know why that is. Any suggestions?
function [y] = test_function_1(x);
y = x + x.^2 + exp(x) + 2*cos(x/2) - 1
end
function [int_f, increment] = int_f_1 (a, b, n);
f = #test_function_1;
h = a + b ./ n
increments = h
int_f = integral(h, f)
end

How to plot Iterations in Julia

I coded a function picircle() that estimates pi.
Now I would like to plot this function for N values.
function Plotpi()
p = 100 # precision of π
N = 5
for i in 1:N
picircle(p)
end
end
3.2238805970149254
3.044776119402985
3.1641791044776117
3.1243781094527363
3.084577114427861
Now I am not sure how to plot the function, I tried plot(PP()) but it didn't work
Here I defined picircle:
function picircle(n)
n = n
L = 2n+1
x = range(-1, 1, length=L)
y = rand(L)
center = (0,0)
radius = 1
n_in_circle = 0
for i in 1:L
if norm((x[i], y[i]) .- center) < radius
n_in_circle += 1
end
end
println(4 * n_in_circle / L)
end
Your problem is that your functions don't actually return anything:
julia> x = Plotpi()
3.263681592039801
3.0646766169154227
2.845771144278607
3.18407960199005
3.044776119402985
julia> x
julia> typeof(x)
Nothing
The numbers you see are just printed to the REPL, and print doesn't return any value:
julia> x = print(5)
5
julia> typeof(x)
Nothing
So you probably just want to change your function so that it returns what you want to plot:
julia> function picircle(n)
n = n
L = 2n+1
x = range(-1, 1, length=L)
y = rand(L)
center = (0,0)
radius = 1
n_in_circle = 0
for i in 1:L
if norm((x[i], y[i]) .- center) < radius
n_in_circle += 1
end
end
4 * n_in_circle / L
end
Then:
julia> x = picircle(100)
3.263681592039801
julia> x
3.263681592039801
So now the value of the function is actually returned (rather than just printed to the console). You don't really need a separate function if you just want to do this multiple times and plot the results, a comprehension will do. Here's an example comparing the variability of the estimate with 100 draws vs 50 draws:
julia> using Plots
julia> histogram([picircle(100) for _ ∈ 1:1_000], label = "100 draws", alpha = 0.5)
julia> histogram!([picircle(20) for _ ∈ 1:1_000], label = "20 draws", alpha = 0.5)

Piecewise Functions in R

I'm trying to plot a piecewise function in R that is equal to -3 if x < 0, 1/3 * x^3 if x is between 0 and 5 (inclusive), and 4x otherwise. The function I've been running seems to work, but the plot returns an error message. The code I wrote is:
g <- function(x) {
if (x < 0)
-3 # first component
else if (x >= 0 & x <= 5)
(1/3) * x #second component
else
4*x # third component
}
Then when I try to plot it with
plot(g, -20, 20)
I get
Error in curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab, :
'expr' did not evaluate to an object of length 'n'
In addition: Warning message:
In if (x < 0) -3 else if (x >= 0 & x <= 5) (1/3) * x else 4 * x :
the condition has length > 1 and only the first element will be used
I can't quite figure out how to troubleshoot this, and the 'ifelse' function returned a dark black line when I attempted to plot it, which I'd prefer to avoid, so this seems to be my best bet.
I would greatly appreciate any insights.

Making closures type-stable dependent on the captured variable

For the function
function function_maker(N)
if N == 1
x = 1.0
else
x = 1
end
f(y) = x+y
end
I want the output of this to not be type-stable, but I want it to generate an f that is type-stable, i.e. uses the type of x determined by the value of N to generate a function dependent on N. Basically, I want the functions that come out of this to be performant, but the function_maker itself doesn't need to be performant because it's only used in the global scope or above a function barrier.
f = function_maker(1)
#code_warntype f(1)
Variables:
#self#::#f#9
y::Int64
Body:
begin
return ((Core.getfield)((Core.getfield)(#self#::#f#9, :x)::ANY, :contents)::ANY + y::Int64)::ANY
end::ANY
This doesn't happen by default. I tried f(y) = x::typeof(x)+y but that didn't work either. Is there a simple way to do this?
There's:
julia> function function_maker2(N)
if N == 1
let x = 1.0
return f(y) = x + y
end
else
let x = 1
return f(y) = x + y
end
end
end
function_maker2 (generic function with 1 method)
julia> f2 = function_maker2(1)
(::f) (generic function with 1 method)
julia> #code_warntype f2(1)
Variables:
#self#::#f#5{Float64}
y::Int64
Body:
begin
return (Base.add_float)((Core.getfield)(#self#::#f#5{Float64}, :x)::Float64, (Base.sitofp)(Float64, y::Int64)::Float64)::Float64
end::Float64
This version separates the x in each branch inside let blocks. Otherwise the compiler seems to get confused.

Mysql: Trim number to be between X and Y MIN/MAX

I don't know the terms or the exact word used for this, but I'm looking for a function inside MySQL that can trim a number to be between X and Y.
For example, something like this:
SELECT TRIM_NUMBER(NUMBER, MIN, MAX);
If I do: TRIM_NUMBER(50, 1, 100) it should be fine, and return 50.
But if I do something like: TRIM_NUMBER(999, 1, 100) it should return 100, because it's the MAX value I'v set it to. The same thing should apply for MIN.
Is there any such function included in MySQL ?
Try this
SELECT GREATEST(LEAST(NUMBER, 100), 1);
There isn't anything built in, but your code it yourself, like this:
select if(num < 1, 1, if (num > 100, 100, num))
If you want the "overkill" of a function, here's a suggestion:
create function trimNumber(x double, floorValue double, ceilValue double) returns double
begin
declare ans double;
if x >= floorValue and x <= ceilValue then
set ans = x;
else
if x < floorValue then
set ans = floorValue;
else
set ans = ceilValue;
end if;
end if;
return ans;
end
I think you are looking for something like that(from MySQL Reference Manual):
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
Just adding this because it is the ANSI standard way of expressing this:
select (case when num < 1 then 1
when num > 100 then 100
else num
end) as TrimmedNum