Julia | Error with Array Length when It Contains Division - julia

I have a problem in Julia, when the array length is variable and contains a division.
For example
length_of_array = n * (n + 1) / 2
array = Array{Float64,1}(length_of_array)
It returns an error related to "convert".
Thank you for your time.

You can only use integers to index into arrays. Division, /, always returns floats, hence the error. Instead of /, use the div function. You can also use the unicode operator, ÷, like this
length_of_array = (n * (n + 1)) ÷ 2

Related

Tensor mode n product in Julia

I need tensor mode n product.
The defination of tenosr mode n product can be seen here.
https://www.alexejgossmann.com/tensor_decomposition_tucker/
I found python code.
I would like to convert this code into julia.
def mode_n_product(x, m, mode):
x = np.asarray(x)
m = np.asarray(m)
if mode <= 0 or mode % 1 != 0:
raise ValueError('`mode` must be a positive interger')
if x.ndim < mode:
raise ValueError('Invalid shape of X for mode = {}: {}'.format(mode, x.shape))
if m.ndim != 2:
raise ValueError('Invalid shape of M: {}'.format(m.shape))
return np.swapaxes(np.swapaxes(x, mode - 1, -1).dot(m.T), mode - 1, -1)
I have found another answer using Tensortoolbox.jl
using TensorToolbox
X=rand(5,4,3);
A=rand(2,5);
ttm(X,A,n) #X times A[1] by mode n
One way is:
using TensorOperations
#tensor y[i1, i2, i3, out, i5] := x[i1, i2, i3, s, i5] * a[out, s]
This is literally the formula given at your link to define this, except that I changed the name of the summed index to s; you can you any index names you like, they are just markers. The sum is implicit, because s does not appear on the left.
There is nothing very special about putting the index out back in the same place. Like your python code, #tensor permutes the dimensions of x in order to use ordinary matrix multiplication, and then permutes again to give y the requested order. The fewer permutations needed, the faster this will be.
Alternatively, you can try using LoopVectorization, Tullio; #tullio y[i1, i2, ... with the same notation. Instead of permuting in order to call a library matrix multiplication function, this writes a pure-Julia version which works with the array as it arrives.

Cumulative Integration Options With Julia

I have two 1-D arrays in which I would like to calculate the approximate cumulative integral of 1 array with respect to the scalar spacing specified by the 2nd array. MATLAB has a function called cumtrapz that handles this scenario. Is there something similar that I can try within Julia to accomplish the same thing?
The expected result is another 1-D array with the integral calculated for each element.
There is a numerical integration package for Julia (see the link) that defines cumul_integrate(X, Y) and uses the trapezoidal rule by default.
If this package didn't exist, though, you could easily write the function yourself and have a very efficient implementation out of the box because the loop does not come with a performance penalty.
Edit: Added an #assert to check matching vector dimensions and fixed a typo.
function cumtrapz(X::T, Y::T) where {T <: AbstractVector}
# Check matching vector length
#assert length(X) == length(Y)
# Initialize Output
out = similar(X)
out[1] = 0
# Iterate over arrays
for i in 2:length(X)
out[i] = out[i-1] + 0.5*(X[i] - X[i-1])*(Y[i] + Y[i-1])
end
# Return output
out
end

How to shuffle parts of a function represented as a sum in R?

If I have any numerical function in R such as :
objFun=function(x) return(x^2+x+1)
How can I shuffle parts of any function in R using a uniform law ?
Example :
The Parts of "objFun" are x^2 & x & 1.
First I need to retrieve the number of components which is n=3, then I should store x^2 & x & 1 in a table with dimension=3.
After that, I can store those parts in a variable tmp such as :
if (uniform law return 1 ) then : tmp= x^2
if (uniform law return 2 ) then : tmp= x
if (uniform law return 3) then : tmp= 1
I didn't give my try because I don't know how to divide a numerical function in R.
It is not clear how "generic" your "uniform law" is. It appears that you want to separate elements in a polynomial expression. Assuming that, and assuming that everything else in a simple function is irrelevant, this would work as a starting point:
objFun=function(x) return(x^2+x+1)
objFun
functionElements <- function(fn) {
# Regular expression of the function body
# Remove anything ahead of an open parenthesis (
# Remove anything after a close parenthesis )
# split on the 4 main arithmetic functions, +, -, * and /
# double backslash means "match the next character exactly", since +, *, -, / have regular expression meanings
# | means "or"
splitElements <- strsplit(split = ".*\\(|\\+|\\*| |\\).*|\\/|\\-", deparse(body(fn)))[[1]]
# remove empty parts ('non zero character')
splitElements <- splitElements[nzchar(splitElements)]
splitElements
}
functionElements(objFun)
It is not clear how you wanted the tmp variable to be, but from the above you could modify to get what you want.

Store elements in a vector Fortran

I have a very simple do loop in which I want to save (to store) the elements of a vector that is computed in the cycle to another one, such as I can recall the elements of this second vector outside the loop.
My naively test is as follow:
program test
implicit none
integer :: num,i
real*8, DIMENSION(3, 1) :: pos
real*8, dimension(:),allocatable :: x(:)
real*8 :: step,delta
pos = 0.0 ! clear the vector all components are equal to zero
pos(1,1)=1. ! only first elements of the vector 'pos' of object 1 is diff. from zero
num=1000
delta = 1.
step = 0.
allocate(x(num)) ! allocate a vector with dimension equal to num
x=0.
do while ( step < num )
pos(1,1) = pos(1,1) + 0.5d0 ! move the objects
x=pos(1,1) ! store the elements of vector 'pos' in vector 'x'
step = step + delta
end do
print*, x(120) ! print the 120th elements of the vector x
end program test
I think the problem is on how i pass the elements from 'pos' to 'x' vector.
Thanks a lot for your help.
This statement
allocate(x(num)) ! allocate a vector with dimension equal to num
makes x a vector with num (i.e. 1000) elements. The next statement
x=0.
sets every element of x to 0.0. So far so good. Then the code enters the loop where this statement
x=pos(1,1) ! store the elements of vector 'pos' in vector 'x'
repeatedly sets every element of x to the latest value of pos(1,1). That's probably not what you want to do. I think the easiest fix would be to rewrite the loop like this
do step = 1,1000
pos(1,1) = pos(1,1) + 0.5d0 ! move the objects
x(step) = pos(1,1) ! store the elements of vector 'pos' in vector 'x'
end do
I'm not sure exactly what you are trying to do, it looks as if you are trying to populate x with the terms in the arithmetic series 1 + n*0.5, n = [0,999]. A neater way to do that might be to modify what you have so that x is indexed from 0, perhaps
allocate(x(0:num-1))
and then simply use a loop such as
do step = 1,999
x(step) = x(step-1)+0.5
end do
I'm not sure why you involve pos in setting the values of x at all.

New to SML / NJ. Making a custom insert function

Define a function that, given a list L, an object x, and a positive
integer k, returns a copy of L with x inserted at the k-th position.
For example, if L is [a1, a2, a3] and k=2, then [a1, x, a2, a3] is
returned. If the length of L is less than k, insert at the end. For
this kind of problems, you are supposed not to use, for example, the
length function. Think about how the function computes the length. No
'if-then-else' or any auxiliary function.
I've figured out how to make a function to find the length of a list
fun mylength ([]) = 0
| mylength (x::xs) = 1+ mylength(xs)
But, as the questions states, I can't use this as an auxiliary function in the insert function. Also, i'm lost as to how to go about the insert function? Any help or guidance would be appreciated!
Here's how to do this. Each recursive call you pass to the function tail of the list and (k - 1) - position of the new element in the tail of the list. When the list is empty, you construct a single-element list (which was given to you); when k is 0, you append your element to what's left from the list. On the way back, you append all heads of the list that you unwrapped before.
fun kinsert [] x k = [x]
| kinsert ls x 0 = x::ls
| kinsert (l::ls) x k = l::(kinsert ls x (k - 1))
I used a 0-indexed list; if you want 1-indexed, just replace 0 with 1.
As you can see, it's almost the same as your mylength function. The difference is that there are two base cases for recursion and your operation on the way back is not +, but ::.
Edit
You can call it like this
kinsert [1,2,3,4,5,6] 10 3;
It has 3 arguments; unlike your length function, it does not wrap arguments in a tuple.
Here's how I'd approach it. The following assumes that the list item starts from zero.
fun mylength (lst,obj,pos) =
case (lst,obj,pos) of
([],ob,po)=>[ob]
| (xs::ys,ob,0) => ob::lst
| (xs::ys,ob,po) => xs::mylength(ys,obj,pos-1)

Resources