Passing 2d array to function in Lua - function

It is possible to pass 2d array to a function as a paramter ?
I initialized an array like this :
tab={}
for i=1, 10 do
tab[i]={}
for z=1, 10 do
tab[i][z]= 0
end
end
and i have function like this :
function foo(data)
...
x = data[i][z] -- here i got error
...
end
The gave the error message attempt to index field '?' (a nil value)
All variables are declared and initialized.

Your code should work if it is initialized properly.
For example, the below code sample will output 3:
function foo(data)
local i, z = 1, 2
print(data[i][z])
end
local tab={}
for i=1, 10 do
tab[i]={}
for z=1, 10 do
tab[i][z]= i + z
end
end
foo(tab)

Maybe you can share the rest of your code? The following runs with no error:
tab={}
for i=1, 10 do
tab[i]={}
for z=1, 10 do
tab[i][z]= 0
end
end
function foo(data)
print(data[3][2])
end
foo(tab)

The gave the error message attempt to index field '?' (a nil value)
I got such errors while changing metatable of some variable.

Related

Declare a Julia function that returns a function with a specific signature

How can I declare a Julia function that returns a function with a specific signature. For example, say I want to return a function that takes an Int and returns an Int:
function buildfunc()::?????
mult(x::Int) = x * 2
return mult
end
What should the question marks be replaced with?
One thing needs to be made clear.
Adding a type declaration on the returned parameter is just an assertion, not part of function definition. To understand what is going on look at the lowered (this is a pre-compilation stage) code of a function:
julia> f(a::Int)::Int = 2a
f (generic function with 1 method)
julia> #code_lowered f(5)
CodeInfo(
1 ─ %1 = Main.Int
│ %2 = 2 * a
│ %3 = Base.convert(%1, %2)
│ %4 = Core.typeassert(%3, %1)
└── return %4
)
In this case since the returned type is obvious this assertion will be actually removed during the compilation process (try #code_native f(5) to see yourself).
If you want for some reason to generate functions I recommend to use the #generated macro. Be warned: meta-programming is usually an overkill for solving any Julia related problem.
#generated function f2(x)
if x <: Int
quote
2x
end
else
quote
10x
end
end
end
Now we have a function f2 where the source code of f2 is going to depend on the parameter type:
julia> f2(3)
6
julia> f2(3.)
30.0
Note that this function generation is actually happening during the compile time:
julia> #code_lowered f2(2)
CodeInfo(
# REPL[34]:1 within `f2'
┌ # REPL[34]:4 within `macro expansion'
1 ─│ %1 = 2 * x
└──│ return %1
└
)
Hope that clears things out.
You can use Function type for this purpose. From Julia documentation:
Function is the abstract type of all functions
function b(c::Int64)::Int64
return c+2;
end
function a()::Function
return b;
end
Which prints:
julia> println(a()(2));
4
Julia will throw exception for Float64 input.
julia> println(a()(2.0));
ERROR: MethodError: no method matching b(::Float64) Closest candidates are: b(::Int64)

Maxima add current loop iteration to filename

I have code similar to the one below, where a function with a parameter depending on the loop iteration is plotted after every iteration. I would like to save the plot with the name trigplot_i.ps where i is the iteration number, but don't know how.
I have tried trigplot_"i".ps but didn't work, and have not been able to find how to cast i to a string either.
I'm a beginner so any help is very welcome.
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10 do
(plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file,"./trigplot_i.ps"],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
code after edits gives an error:
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10
do block([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", myfile),
plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file, myfile],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
error:
"declare: argument must be a symbol; found "./trigplot_1.ps
-- an error.
To debug this try: debugmode(true);"
Looks good. To construct a file name, try this: sconcat("./trigplot_", i, ".ps") or also you can try: printf(false, "./trigplot_~d.ps", i). My advice is to make that a separate step in the loop, and then you can use it in the call to plot2d, e.g.:
for i:1 thru 10
do block ([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", i, myfile),
plot2d (<stuff goes here>, [ps_file, myfile], <more stuff>));
EDIT: Fixed a bug in printf (omitted argument i).

Julia waits for function to finish before printing message in a loop

I have a function in Julia that requires to do things in a loop. A parameter is passed to the loop, and the bigger this parameter, the slower the function gets. I would like to have a message to know in which iteration it is, but it seems that Julia waits for the whole function to be finished before printing anything. This is Julia 1.4. That behaviour was not on Julia 1.3.
A example would be like this
function f(x)
rr=0.000:0.0001:x
aux=0
for r in rr
print(r, " ")
aux+=veryslowfunction(r)
end
return aux
end
As it is, f, when called, does not print anything until it has finished.
You need to add after the print command:
flush(stdout)
Explanation
The standard output of a process is usually buffered. The particular buffer size and behavior will depend on your system setting and perhaps the terminal type.
By flushing the buffer you make sure that the contents is actually sent to the terminal.
Alternatively, you can also use a library like ProgressLogging.jl (needs TerminalLoggers.jl to see actual output), or ProgressMeter.jl, which will automatically update a nicely formatted status bar during each step of the loop.
For example, with ProgressMeter, a call to
function f(x)
rr=0.000:0.0001:x
aux=0
#showprogress for r in rr
aux += veryslowfunction(r)
end
return aux
end
will show something like (in the end):
Progress: 100%|██████████████████████████████████████████████████████████████| Time: 0:00:10
Again I can't reproduce the behaviour in my terminal (it always prints), but I wanted to add that for these types of situations the #show macro is quite neat:
julia> function f(x)
rr=0.000:0.0001:x
aux=0
for r in rr
#show r
aux+=veryslowfunction(r)
end
return aux
end
f (generic function with 1 method)
julia> f(1)
r = 0.0
r = 0.0001
r = 0.0002
...
It uses println under the hood:
julia> using MacroTools
julia> a = 5
5
julia> prettify(#expand(#show a))
quote
Base.println("a = ", Base.repr($(Expr(:(=), :ibex, :a))))
ibex
end

number(X) as function parameter or return value generates PLS 00103 error

I have the following function definition:
create or replace FUNCTION checkXML
(idx in number(19))
return number(19)
is
...
But when I compile it, am getting the following errors,
Error(2,16): PLS-00103: Encountered the symbol "(" when expecting one of the
following: := . ) , # % default character The symbol ":=" was substituted for
"(" to continue.
Error(3,15): PLS-00103: Encountered the symbol "(" when expecting one of the
following: . # % ; is authid as cluster order using external character
deterministic parallel_enable pipelined aggregate result_cache
Change the function declaraction to be
create or replace FUNCTION checkXML
(idx in number)
return number
PL/SQL doesn't accept length or precision specifiers on parameters or return types.
Share and enjoy.

Passing a function as a parameter in a MATLAB function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Passing a function as argument to another function
Below is a simple code for the bisection method. I would like to know how to be able to pass in any function I choose as a parameter instead of hard coding functions.
% This is an implementation of the bisection method
% for a solution to f(x) = 0 over an interval [a,b] where f(a) and f(b)
% Input: endpoints (a,b),Tolerance(TOL), Max # of iterations (No).
% Output: Value p or error message.
function bjsect(a,b,TOL,No)
% Step 0
if f(a)*f(b)>0
disp('Function fails condition of f(a),f(b) w/opposite sign'\n);
return
end
% Step 1
i = 1;
FA = f(a);
% Step 2
while i <= No
% Step 3
p = a +(b - a)/2;
FP = f(p);
% Step 4
if FP == 0 || (b - a)/2 < TOL
disp(p);
return
end
% Step 5
i = i + 1;
% Step 6
if FA*FP > 0
a = p;
else
b = p;
end
% Step 7
if i > No
disp('Method failed after No iterations\n');
return
end
end
end
% Hard coded test function
function y = f(x)
y = x - 2*sin(x);
end
I know this is an important concept so any help is greatly appreciated.
The simplest method is using anonymous functions. In your example, you would define your anonymous function outside bjsect using:
MyAnonFunc = #(x) (x - 2 * sin(x));
You can now pass MyAnonFunc into bjsect as an argument. It has the object type of function handle, which can be validated using isa. Inside bjsect simply use MyAnonFunc as if it is a function, ie: MyAnonFunc(SomeInputValue).
Note, you can of course wrap any function you've written in an anonymous function, ie:
MyAnonFunc2 = #(x) (SomeOtherCustomFunction(x, OtherInputArgs));
is perfectly valid.
EDIT: Oops, just realized this is almost certainly a duplicate of another question - thanks H. Muster, I'll flag it.