Parse 2D-Array in Julia - julia

In Julia I can create 2D-arrays with
[1 2 3 4 ; 5 6 7 8]
2×4 Array{Int64,2}:
1 2 3 4
5 6 7 8
The problem is, that I need to parse a 2D-array supplied as an argument to a script - that is as a String.
For example
$ julia script.jl "[1 2 3 4 ; 5 6 7 8]"
and in the script something like:
c = parse.(ARGS[1])
and c should be a 2×4 array.
I am flexible regarding the format of the input String.
The usecase is, that I want to call an optimization problem implemented in Julia + JuMP from within Java.

Check out the readdlm function, which will allow you to parse the text received from ARGS as an array:
using DelimitedFiles
a = readdlm(IOBuffer(ARGS[1]),',',';')
display(a)
Running:
$ julia argscript.jl "1,2,3,4;5,6,7,8"
2×4 Array{Float64,2}:
1.0 2.0 3.0 4.0
5.0 6.0 7.0 8.0
You can force the array element type in the script:
a = readdlm(IOBuffer(ARGS[1]),',',Int,';')
You could even enforce the matrix dimensions by passing two more arguments:
using DelimitedFiles
n = parse(Int,ARGS[1])
m = parse(Int,ARGS[2])
a = readdlm(IOBuffer(ARGS[3]),',',Int,';',dims=(n,m))
Running:
$ julia argscript.jl 2 3 "3,2,1;2,6,8"
2×3 Array{Int64,2}:
3 2 1
2 6 8
$ julia argscript.jl 2 4 "3,2,1;2,6,8"
ERROR: LoadError: at row 2, column 1 : ErrorException("missing value at row 1 column 4"))

Related

How to delete a selected element in a range construct in Julia?

From here I found that in a range construct one cannot find and replace its elements via array functions... How can be do it anyway?
Suppose I want to delete the elements 2,6,7,8,13,19 in range(1, step=1, stop=21). Or more generally, suppose a is a random array that contains numbers in the range [1,21] and one wants to delete these elementes in the given range.
You cannot delete from a range object, since that is immutable, but you can filter it:
julia> filter(x -> x ∉ [2,6,7,8,13,19], a)
15-element Array{Int64,1}:
1
3
4
5
9
10
11
12
14
15
16
17
18
20
21
However, if a is a "real" array, you can use filter! to operate in-place.
Another solution that if often convenient is to use InvertedIndices.jl package which exports Not and you can just use indexing:
julia> r = 1:21
1:21
julia> x = [2,6,7,8,13,19]
6-element Array{Int64,1}:
2
6
7
8
13
19
julia> r[Not(x)]
15-element Array{Int64,1}:
1
3
4
5
9
10
11
12
14
15
16
17
18
20
21

R - Print list in file and recover list

I have a list that looks like this:
> indices
$`48-168`
$`48-168`$`1`
[1] 1 2 3 4 5 6 7 8 9 10
$`60-180`
$`60-180`$`1`
[1] 1 2 3 4 5 6 7 8 9 10
$`180-300`
$`180-300`$`1`
[1] 1 2
$`180-300`$`4`
[1] 4 5 6 7 8 9 10
$`180-300`$`3`
[1] 3
I want to print it somehow in a file and then recover the same list later.
I though printing the object given by unlist(as.relistable(obj)) and use relist later but then I do not know how to recover the information from the file.
Given that your data is not particularly well structured, you might want to just use save() here, and save the original R list object:
save(indices, file="/path/to/your/file.txt")
When you want to load indices again, use the load() function:
load(file="/path/to/your/file.txt")

Writing Data into columns in a file (IDL)

I am trying to write some data into columns in IDL.
Let's say I am calculating "k" and "k**2", then I would get:
1 1
2 4
3 9
. .
and so on.
If I write this into a file, it looks like this:
1 1 2 4 3 9 . .
My corresponding code looks like this:
pro programname
openw, 1, "filename"
.
. calculating some values
.
printf, 1, value1, value2, value3
close,1
end
best regards
You should probably read the IDL documentation on formatted output, to get all of the details.
I don't understand your "value1, value2, value3" in your printf. If I were going to do this, I would have two variables "k" and "k2". Then I would print using either a transpose or a for loop:
IDL> k = [1:10]
IDL> k2 = k^2
IDL> print, transpose([[k], [k2]])
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
IDL> for i=0,n_elements(k)-1 do print, k[i], k2[i]
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
By the way, if you are going to use stack overflow you should start "accepting" the correct answers.
It sounds like you have two vectors. One with single values and one with square values. Here's what you could do:
pro programname
openw, f, "filename", /GET_LUN
.
. calculating some values for k
.
k2 = k^2 ;<---This is where you square your original array.
;Merge the vectors into a single array. Many ways to do this.
k = strtrim(k,2) ;<----------------------------Convert to string format
k2 = strtrim(k2,2) ;<--------------------------Convert to string format
merge = strjoin(transpose([[k],[k2]]),' ') ;<--Merge the arrays
;Now output your array to file the way you want to
for i=0L, n_elements(k)-1 do printf, f, merge[i]
;Close the file and free the logical file unit
free_lun, f
end

Functions without arguments

I'm not sure about this. Here is an example of a function which does not work:
myfunction<-function(){
mydata=read_excel("Square_data.xlsx", sheet = "Data", skip=0)
mydata$Dates=as.Date(mydata$Dates, format= "%Y-%m-%d")
mydata.ts=ts(mydata, start=2006, frequency=1)
}
The files do not load. When I execute each command line by line in R the files are loaded, so there's no problem with the commands. My question is, can I run a function such as myfunction to load the files? Thanks.
Last statement in function is an assignment If the last executed statement in a function is an assignment then it will not display on the console unless you use print but if the function result is assigned then you can print the assigned value later. For example, using the built in BOD data frame:
> f <- function() bod <- BOD
> f() # no result printed on console because f() was not explicitly printed
> print(f()) # explicitly print
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
> X <- f() # assign and then print the assigned value
> X
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
Last statement in function is expression producing a result If the last statement produces a value rather than being an assignment then a result is printed on the console. For example:
> g <- function() BOD
> g()
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
Thus make sure that the last statement in your function is not an assignment if you want it to display on the console automatically.
Note 1: sourcing code Also, note that if your code is sourced using a source() statement or if the code is called by another function then it also won't print automatically on the console unless you use a print.
Note 2: Two results Regarding some comments to the question, if you want to output two results then output them in a named list. For example. this outputs a list with components named BOD and BOD2:
h <- function() list(BOD = BOD, BOD2 = 2*BOD)
h()
$BOD
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
$BOD2
Time demand
1 2 16.6
2 4 20.6
3 6 38.0
4 8 32.0
5 10 31.2
6 14 39.6
We could refer to them like this:
> H <- h()
> H$BOD
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
> H$BOD2
Time demand
1 2 16.6
2 4 20.6
3 6 38.0
4 8 32.0
5 10 31.2
6 14 39.6
Note 3: <<- operator Regarding the comments to the question, in general, using the <<- operator should be avoided because it undesirably links the internals of your function to the global workspace in an invisible and therefore error-prone way. If you want to return a value it is normally best to return it as the output of the function. There are some situations where <<- is warranted but they are relatively uncommon.
Sure. Just give it a value to be returned:
myfunction<-function(){
mydata=read_excel("Square_data.xlsx", sheet = "Data", skip=0)
mydata$Dates=as.Date(mydata$Dates, format= "%Y-%m-%d")
ts(mydata, start=2006, frequency=1) # The last object is returned by an R function
}
so calling dat <- myfunction() will make dat the ts-object that was created inside the function.
P.S.: There also in a return function in R. As a best practice only use this if you want to return an object early, e.g. in combination with if

How to create lagged variables in Julia?

Is there a function to create lagged variables in Julia without resorting any packages?
Specifically, I want to emulate the R's embed function in Julia.
> embed(1:8, 3)
[,1] [,2] [,3]
[1,] 3 2 1
[2,] 4 3 2
[3,] 5 4 3
[4,] 6 5 4
[5,] 7 6 5
[6,] 8 7 6
After a couple of hours of browsing Julia manual, I gave up looking for suitable function in Julia. This ugly function (by R standard) is what I have so far. Is there any built-in function or any room for improvement?
julia> function embed(x, k)
n = length(x)
m = zeros(n - k + 1, k)
for i in 1:k
m[:, i] = x[(k-i+1):(n-i+1)]
end
return m
end
embed (generic function with 1 method)
julia> embed(1:8,3)
6x3 Array{Float64,2}:
3.0 2.0 1.0
4.0 3.0 2.0
5.0 4.0 3.0
6.0 5.0 4.0
7.0 6.0 5.0
8.0 7.0 6.0
You can dismiss zeros for cell to skip initialization. You can also do
embed(x,k) = hcat([x[i+k-1:-1:i] for i in 1:length(x)-k+1]...)'
Explanation
Create reverse stride indexes using [i+k-1:-1:i] and for
Take that list of items, and make it the arguments of hcat by using ...
Concatenate the strides (passed as arguments)
Transpose the result using '
EDIT: Assuming length(x) ⋙ k, you can also use:
embed(x,k) = hcat([x[k-i+1:length(x)-i+1] for i in 1:k]...)
Which gives the same results, but iterates less, and thus does less allocations.

Resources