Populating an array using a FOR loop and a function - julia

I was expecting that the following code would populate E with random 1's and 0's, but that does not happen. I cannot figure out why.
Pkg.add("StatsBase")
using StatsBase
function randomSample(items,weights)
sample(items, Weights(weights))
end
n = 10
periods = 100
p = [ones(n,periods)*0.5]
E = fill(NaN, (n,periods))
for i in 1:periods
for ii in 1:n
E(ii,i) = randomSample([1 0],[(p(ii,i)), 1 - p(ii,i)])
end
end
E

The statement:
E(ii,i) = randomSample([1 0],[(p(ii,i)), 1 - p(ii,i)])
defines a local function E and is not an assignment operation to a matrix E. Use
E[ii,i] = randomSample([1, 0],[p[ii,i], 1 - p[ii,i]])
(I have fixed additional errors in your code so please check out the differences)
and for it to run you should also write:
p = ones(n,periods)*0.5

Related

Julia UndefVarError on Metaprogramming

I'm trying to do a solver for equations. When I run the code the X variable appears to be undefined, but it prints out perfectly. What am I missing?
I should give the program some numbers, than operations as Macros and it should create an outer product matrix of the operations applied.
function msu()
print("Insert how many values: ")
quantity = parse(Int64, readline())
values = []
for i in 1:quantity
println("x$i")
num1 = parse(Float64, readline())
push!(values, num1)
end
println(values)
print("How many operations? ")
quantity = parse(Int64, readline())
ops = []
for i in 1:quantity
push!(ops, Meta.parse(readline()))
end
mat = zeros((quantity, quantity))
for i in 1:length(mat)
sum = 0
for j in 1:length(values)
# here begins problems, the following prints are for debugging purpose
print(length(values))
func = Meta.parse("$(ops[convert(Int64, ceil(j / quantity))]) * $(ops[convert(Int64, j % quantity)])")
print(func)
x = values[j]
println(x)
sum += eval(func)
end
mat[i] = sum
end
println(mat)
end
msu()
The original code was in Spanish, if you find any typo it's probably because I skipped a translation.

In Julia, a value accessed from a matrix failed to be used as an argument in a function

First, I have a function called permeability.
# permeabiliy function
# L is short for the Lable
mu_0 = 4 * pi * 10^(-7);
mu_r_core = 50;
mu_r_air = 1;
L = Int16;
function permeability(L)
if L in 1:4
if L !== 3
return mu = mu_r_air * mu_0
else
return mu = mu_r_core * mu_0
end
else
println("null") #print output in a new line
end
end
Then, I have a matrix called domain, which is shown below,
domain
2392-element Array{Int16,1}:
1
1
3
1
...
When I called permeability(domain[3]), the output is,
L = domain[3]
permeability(L)
the output is
1.2566370614359177e-6
However, when I simply called permeability(3),
permeability(3)
the output is
6.283185307179588e-5
So, it seems that the value passed from matrix domain is just "1", but in this case, domain[3] should be 3 and the result should be the same in these 2 cases.
Can someone please tell me where I was wrong?
The problem is that your array stores Int16 while 3 is an Int64. L!==3 requires L to be of the same type as 3 ie Int64. You wanted instead L!=3. Your confusion probably comes from the fact that != is the inverse of == while !== is the inverse of ===

Multiple outputs used repeatedly in for loop Julia

I am using Julia and I've designed a for loop that takes the outputs of a function in one loop and uses them as the input of that function in the next loop (and over and over). When I run this code, Julia flags an "undefined" error, however, if I run the code in debug mode, it executes perfectly. For example, the code looks like this:
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
for ii in 1:length(x)
if ii == 1
a = 0
b = "string something"
c = ""
d = false
end
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
What am I doing wrong here?
An issue with your code is that for introduces a new scope for each iteration of the loop. That is to say: variable a created within the loop body at iteration 1 is not the same as variable a created within the loop body at iteration 2.
In order to fix your problem, you should declare variables outside the loop, so that at each iteration, references to them from within the loop body would actually refer to the same variables from the enclosing scope.
I'd go with something like this:
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
# Let's create a local scope: it's good practice to avoid global variables
let
# All these variables are declared in the scope introduced by `let`
a = 0
b = "string something"
c = ""
d = false
for ii in 1:10 #length(x)
# now these names refer to the variables declared in the enclosing scope
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
end

Julia NLopt force stops before the first iteration

I'm using NLopt for a constrained maximization problem. Regardless of the algorithm or start values, the optimization program is force stopped even before the first iteration (or so I assume because it gives me the initial value). I've attached my code here. I'm trying to find probabilities attached to a grid such that a function is maximized under some constraints. Any help is appreciated.
uk = x -> x^0.5
function objective(u,p,grd)
-p'*u.(grd)
end
function c3(grd,p)
c =[]
d =[]
for i=1:length(grd)
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
end
return append!(d-c,-p)
end
function c4(grd,p)
return (grd .* p)-quadgk(x,0,1)
end
grd = n -> collect(0:1/n:1)
opt = Opt(:LD_SLSQP,11)
inequality_constraint!(opt, p -> c3(grd(10),p))
inequality_constraint!(opt, p -> -p)
equality_constraint!(opt, p -> sum(p)-1)
equality_constraint!(opt, p -> c4(grd(10),p))
opt.min_objective = p -> objective(-uk, p, grd(10))
k = push!(ones(11)*(1/11))
(minf,minx,ret) = optimize(opt, k)
I'm not a julia developer, but I only know this, if you need exit before complete the loop for is not your best choice, you need do a while with a sentinel variable.
here you have an article that explain you how while with sentinels works
and here you have a julia example changing your for to a while with a sentinel that exit after the third loop
i = 1
third = 0
while i < length(grd) && third != 1
# of course you need change this, it is only an example that will exit in the 3 loop
if i == 3
third = 1
end
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
i += 1
end

ndgrid - input and output from cell array

I am converting some code from Matlab to Scilab and ran into trouble trying to use Scilab 'ndgrid' function with input and output from cell array.
Specifically, I use ndgrid with an a priori unknown number of vectors (contained in a cell array) and intend to get the output grid matrices in a cell array.
In Matlab the code looks like that:
v = {0:3,0:3}; // not necessarily of length 2 (dynamically set)
G = cell(1,2);
[G{:}] = ndgrid(v{:});
I can't obtain similar behaviour using Scilab (neither for the input, nor for the output).
For the input, Scilab returns ndgrid: Wrong type for argument #1: Booleans, Integers, Decimals, Complexes, Polynomials, Rationals or Texts expected.
I hope a workaround exists. Thanks for your help!
v = list(0:3, 0:2); // not necessarily of length 2 (dynamically set)
G = list();
c = strcat(msprintf("G(%i)\n",(1:length(v))'),",")
execstr("[" + c + "] = ndgrid(v(:))")
G
does it:
--> c = strcat(msprintf("G(%i)\n",(1:length(v))'),",")
c =
"G(1),G(2)"
--> execstr("[" + c + "] = ndgrid(v(:))")
--> G
G =
(1) : [4x3 constant]
(2) : [4x3 constant]

Resources