Range based slicing with the get and set index functions? - julia

How can I allow for range based slicing with the get and set index functions?
And will they be copies or views? views are preferable.
function Base.getindex(cb::CircularMatrix, I::Vararg{Int,2})
cb.buffer[I[1], _buffer_index_checked(cb, I[2])]
end
function Base.setindex!(cb::CircularMatrix, data, I::Vararg{Int,2})
cb.buffer[I[1], _buffer_index_checked(cb, I[2])] = data
cb
end
s = CircluarMatrix{Int}(5, 5)
s[:, 5]
s[5, :]

Related

Asking for pairs of information on a x_mdialog for scilab

I'm creating a program to calculate the linear regression of data. The program should, when you start, ask for the number of pairs of values (x and y) to be used. And according to the number of pairs that you define, it should go asking for the data to apply the regression (on pairs of X, Y). The program must apply regression for all methods available.
I already have the code for the regressions but the problem that I have is that I don't know how to ask for the data (the pairs of x and y) and for x create a vector, and for y create a separate vector. Also, it can be from 3 pairs to infinite number of pairs.
There are many ways to accomplish what you want. One possible way is to use a for-loop:
Inquiry the users on how many points they want to input, n_pairs, as you said.
Use a for-loop from 1 to n_pairs asking for inputs using x_mdialog.
At each iteration, evaluate the input and store the data.
Something like the following could work for you:
//inquiry how many pairs
n_pairs = x_mdialog("Data acquisition","How many points will you enter?","3");
n_pairs = evstr(n_pairs);
//initialise data
X_data = []; Y_data = [];
for i = 1 : n_pairs
//acquire each pair
pair = x_mdialog("Data acquisition",["X:","Y:"],["",""])
if pair(1) == "" | pair(2) == "" | pair == [] then
//break loop in case of blank input
break
else
//non-blank inputs are stored
X_data(i) = evstr(pair(1));
Y_data(i) = evstr(pair(2));
end
end
//sort values accordint to X
[X_data,idx] = gsort(X_data,"r","i");
Y_data = Y_data(idx);

iterating through a multidimensional array using CartesianRange in julia

I want to retrieve all the elements along the last dimension of an N-dimensional array A. That is, if idx is an (N-1) dimensional tuple, I want A[idx...,:]. I've figured out how to use CartesianRange for this, and it works as shown below
A = rand(2,3,4)
for idx in CartesianRange(size(A)[1:end-1])
i = zeros(Int, length(idx))
[i[bdx] = idx[bdx] for bdx in 1:length(idx)]
#show(A[i...,:])
end
However, there must be an easier way to create the index i shown above . Splatting idx does not work - what am I doing wrong?
You can just index directly with the CartesianIndex that gets generated from the CartesianRange!
julia> for idx in CartesianRange(size(A)[1:end-1])
#show(A[idx,:])
end
A[idx,:] = [0.0334735,0.216738,0.941401,0.973918]
A[idx,:] = [0.842384,0.236736,0.103348,0.729471]
A[idx,:] = [0.056548,0.283617,0.504253,0.718918]
A[idx,:] = [0.551649,0.55043,0.126092,0.259216]
A[idx,:] = [0.65623,0.738998,0.781989,0.160111]
A[idx,:] = [0.177955,0.971617,0.942002,0.210386]
The other recommendation I'd have here is to use the un-exported Base.front function to extract the leading dimensions from size(A) instead of indexing into it. Working with tuples in a type-stable way like this can be a little tricky, but they're really fast once you get the hang of it.
It's also worth noting that Julia's arrays are column-major, so accessing the trailing dimension like this is going to be much slower than grabbing the columns.

Excel vlookup in Julia

I have two arrays in Julia, X = Array{Float64,2} and Y = Array{Float64,2}. I'd like to perform a vlookup as per Excel functionality. I can't seem to find something like this.
the following code returns first matched from s details matrix using related record from a master matrix.
function vlook(master, detail, val)
val = master[findfirst(x->x==val,master[:,2]),1]
return detail[findfirst(x->x==val,detail[:,1]),2]
end
julia> vlook(a,b,103)
1005
A more general approach is to use DataFrame.jl, for working with tabular data.
VLOOKUP is a popular function amongst Excel users, and has signature:
VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
I've never much liked that last argument range_lookup. First it's not clear to me what "range_lookup" is intended to mean and second it's an optional argument defaulting to the much-less-likely-to-be-what-you-want value of TRUE for approximate matching, rather than FALSE for exact matching.
So in my attempt to write VLOOKUP equivalents in Julia I've dropped the range_lookup argument and added another argument keycol_index_num to allow for searching of other than the first column of table_array.
WARNING
I'm very new new to Julia, so there may be some howlers in the code below. But it seems to work for me. Julia 0.6.4. Also, and as already commented, using DataFrames might be a better solution for looking up values in an array-like structure.
#=
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Procedures: vlookup and vlookup_withfailsafe
Purpose : Inspired by Excel VLOOKUP. Searches a column of table_array for
lookup_values and returns the corresponding elements from another column of
table_array.
Arguments:
lookup_values: a value or array of values to be searched for inside
column keycol_index_num of table_array.
table_array: An array with two dimensions.
failsafe: a single value. The return contains this value whenever an element
of lookup_values is not found.
col_index_num: the number of the column of table_array from which values
are returned.
keycol_index_num: the number of the column of table_array to be searched.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=#
vlookup = function(lookup_values, table_array::AbstractArray, col_index_num::Int = 2, keycol_index_num::Int = 1)
if ndims(table_array)!=2
error("table_array must have 2 dimensions")
end
if isa(lookup_values,AbstractArray)
indexes = indexin(lookup_values,table_array[:,keycol_index_num])
if(any(indexes==0))
error("at least one element of lookup_values not found in column $keycol_index_num of table_array")
end
return(table_array[indexes,col_index_num])
else
index = indexin([lookup_values],table_array[:,keycol_index_num])[1]
if(index==0)
error("lookup_values not found in column $keycol_index_num of table_array")
end
return(table_array[index,col_index_num])
end
end
vlookup_withfailsafe = function(lookup_values, table_array::AbstractArray, failsafe, col_index_num::Int = 2, keycol_index_num::Int = 1)
if ndims(table_array)!=2
error("table_array must have 2 dimensions")
end
if !isa(failsafe,eltype(tablearray))
error("failsafe must be of the same type as the elements of table_array")
end
if isa(lookup_values,AbstractArray)
indexes = indexin(lookup_values,table_array[:,keycol_index_num])
Result = Array{eltype(table_array)}(size(lookup_values))
for i in 1:length(lookup_values)
if(indexes[i]==0)
Result[i] = failsafe
else
Result[i] = table_array[indexes[i],col_index_num]
end
end
return(Result)
else
index = indexin([lookup_values],table_array[:,keycol_index_num])[1]
if index == 0
return(failsafe)
else
return(table_array[index,col_index_num])
end
end
end

Julia groupBy name and sum up count

I'm new to Julia and have a simple question. I have a csv file with the following structures: [Category, Name, Count]. I have 2 things I want to create.
1, I want to create a function in julia which groupBy the Category and add up the Counts (Name is ignored). So that the output is [Name, Count]. I will then generate a bar-plot by setting x= Name and y= Count
2, I want to generate multiple plots for each Category where the Count of each Name is plotted on separate bar-plots. So iterative plotting process?
I think I've got the hang of plotting, but I am not sure about how to do the groupBy process. Any help/re-direction to tutorials would be greatly appreciated.
A sample of my data:
(net_worth,khan,14)
(net_worth,kevin,15)
(net_worth,bill,16)
the function I am currently working on:
function wordcount(text,opinion,number)
words= text
counts= Dict()
for w = words
counts[w]= number
end
return counts
end
function wcreduce(wcs)
counts=Dict()
for c in wcs, (k,v) in c
counts[k] = get(counts,k,0)+v
end
return counts
end
I am looking for a function like reduceByKey or GroupByKey I guess.
So I solved this by using the Julia by function on DataFrames,
First load in the data csv using:
data = readtable("iris.csv")
Now its the function by:
function trendingkeys(data::DataFrame,trends::Symbol,funcadd::Function)
by(data, :trends, funcadd -> sum(funcadd[:counts]))
end
I must say. DataFrame is so smart.

Neo4j v2. Are aggregate functions usable as assignment (set) values?

I can return an aggregate such as:
match (u:User)-[:LIKED]->(o:Offer) return count(u) as numLikes
...but I can't assign from it and keep it pre-counted for speed:
match (u:User)-[:LIKED]->(o:Offer) set o.numLikes = count(u)
Is this possible without using two separate statements?
You need to use WITH:
MATCH (u:User)-[:LIKED]->(o:Offer)
WITH o, count(u) AS c
SET o.numLikes = c
You have to complete the aggregation before you can use the aggregated value, you can do this with WITH, something like
MATCH (u:User)-[:LIKED]->(o:Offer)
WITH o, COUNT(u) as numLikes
SET o.numLikes = numLikes

Resources