Maxima: convert matrix to list - symbolic-math

I convert list to matrix in Maxima in following way:
DataL : [ [1,2], [2,4], [3,6], [4,8] ];
DataM: apply('matrix,DataL);
How to do it the other way ? How to convert given matrix DataM into list DataL ?

I know it's late in the game, but for what it's worth, there is a simpler way.
my_matrix : matrix ([a, b, c], [d, e, f]);
my_list : args (my_matrix);
=> [[a, b, c], [d, e, f]]

I'm far from a Maxima expert, but since you asked me to look at this question, here's what I have after a quick look through the documentation.
First, looking at the documentation on matrices yielded only one way of turning matrices in to lists, which is list_matrix_entries. However, this returns a flat list of the entries. To get a nested list structure, something like the following works
DataL : [[1, 2], [2, 4], [3, 6], [4, 8]]; /* Using your example list */
DataM : apply('matrix, DataL); /* and matrix */
DataML : makelist(list_matrix_entries(row(DataM, i)), i, 1, 4);
is(DataML = DataL); /* true */
This is clumsy and probably inefficient. Using the underlying Lisp structure in Maxima (and analogy to Mathematica, which I'm more familiar with) you can examine the heads of DataL and DataM using part:
part(DataL, 0); /* [ */
part(DataM, 0); /* matrix */
Then to convert between the two structures, you can use substpart
is(substpart(matrix, DataL, 0) = DataM); /* true */
is(substpart( "[", DataM, 0) = DataL); /* true */
Using substpart at level 0 is almost the same as using apply, except it works on more than just lists.

Related

Array of numbers in Dart without using List?

In Dart, I need to have a list of numeric values, and in my case, this list never needs to have any special operations done (does not need re-ordering, length queries, add, etc.) on them other than reading the values with one sweep.
Is there an alternative data structure to List where we could store a "list" like this and compare two of them using == or != and not suffer the performance hit of having to use "deep equality"?
In Dart, you need to use the List type to represent an array.
The == operator doesn't use "deep equality" and will just check if two lists are the same object.
List<int> a = [1, 2, 3];
List<int> b = [1, 2, 3];
print(a == b); // false
Fortunately, you can get around this issue without the performance hit of looping through both lists by using the const keyword:
List<int> c = const [4, 5, 6];
List<int> d = const [4, 5, 6];
print(c == d); // true

C equivalent for nested lists (Python)

I am new to C and trying to learn by comparison with Python.
My question is trivial, but I still need some explanations from experts. Here is a Python nested list structure:
L = [1, [2, [3, 4], 5], 6, [7, 8]]
And here is an interesting piece of code (taken from 'Learning Python' by Lutz) to handle nested structures (sum elements):
def sumtree(L):
tot = 0
for x in L:
if not isinstance(x, list):
tot += x
else:
tot += sumtree(x)
return tot
If I pass L into this function I will get 36, which is a sum of elements in L.
How exactly can nested lists and this particular function be translated into C?
What type is every element of L? It can be a number (an int for example in C), or even a list (it's typical for a list to be implemented with structs in C).
In order to achieve that, you would need a generic list (i.e. that the data of every node is of type void*). Notice that C doesn't provide a list from the standard library, you have to write one (here is an example).
Then, in order to get the sum, you would do something like that:
int sumtree(struct listnode * L) {
int tot = 0;
while (L != NULL) {
if(L.data /* TODO: check if it is a number*/)
tot += L.data;
else /* L.data is a sublist */
tot = sumtree(L.data);
list = list->next;
}
return tot;
}
In order to get the type, you need to follow this answer: How do I check if a variable is of a certain type (compare two types) in C?
However, such nested lists in C are not common, and I would advise you to re-approach the issue.

Algorithm for intersection of n arrays in C

I need to write a function which returns the intersection (AND condition) of all the arrays generated in every iteration for an array of queries.
If my query is given by: query[] = {"num>20", "avg==5", "deviation != 0.5"} then, n runs from 0 to length of query. The query is passed on to a function (get_sample_ids) which compares the condition against a list of samples possessing certain information. The returned array numbers from get_sample_ids are the index of the respective samples.
query[] = {"num>20", "avg==5", "deviation != 0.5"}
int intersected_array*;
for n=0:query.length-1
int arr* = get_sample_ids(query[n]);
// n=0: [1, 7, 4, 2, 6]
// n=1: [3, 6, 2]
// n=2: [6, 2]
end;
Expected output: intersected_array* = [6, 2]
I've coded an implementation which has 2 arrays (arr*, temp*). For every array returned in the iteration, it is first stored in the temp* array and the intersection of arr* and temp* is stored in arr*. Is this an optimal solution or what is the best approach?
This is quite efficient but could be tiresome to implement (haven't tried it).
Determine the shortest array. Benefit of using C is that if you don't know their length, you can use the pointers to arrays to determine it if they are placed sequentially in memory.
Make a <entry,boolean> hash map for the entries in shortest. We know the size and if anything it's only going down in next steps.
Iterate through an array. Start by initiating the whole map to false. For each entry check it in map.
Iterate through map deleting all the entries that weren't checked. Set all the values to false.
If there any new arrays left go back to step 3. with a new array.
The result are the keys in the final map.
It looks like much but we didn't have to resort to any high complexity measures. Key to good performance is using hash map because of constant access time.
Alternatively:
Make the map be <entry,int>. This way you can count up all the recurrences and don't have to reset it at every iteration, which adds to complexity.
At the end just compare the number of array's to the the values in map. Those that match are your solution.
Complexity:
Seems like O(n).
First I would sort the arrays in ascending order more easy to preform tasks
you could also zero pad the arrays so all the arrays shall be in the same size
[1, 2, 0, 4, 0, 0, 6, 7]
[0, 2, 3, 4, 0, 0, 6, 7]
[0, 2, 0, 0, 0, 0, 6, 0]
like a matrix so you could easily find the intersection
all this shall take a lot of PC run time
enjoy
Here is Jquery implementation of #ZbyszekKr solution -
I have $indexes as array of arrays for all characters in English alphabets which stores which char is present in which rows. $chars is the array of char string I am trying to filter in my HTML table rows. Below method is a part of larger scheme in filtering rows as a user types, when there are more than say 5000 rows in your table.
PS - There are some obvious redundancies, but those are necessary for my plugin I am making.
function intersection($indexes, $chars){
map = {};
$minLength = Number.MAX_SAFE_INTEGER; $minIdx = 0;
//get shortest array
$.each($chars, function(key, c){
$index = getDiffInNum(c, $initialChar);
$len = $indexes[$index].rows.length;
if($len < $minLength){
$minLength = $len;
$minIdx = $index;
}
});
//put that array values in map
$minCount = 1;
$.each($indexes[$minIdx].rows, function(key, val){
map[val] = $minCount;
});
//iterate through other arrays to figure out count of element
$.each($chars, function(key, c){
$index = getDiffInNum(c, $initialChar);
if($index != $minIdx){
$array = $indexes[$index].rows;
$.each($array, function(key, val){
if(val in map){
map[val] = map[val] + 1;
}
});
$.each(map, function(key, val){
if(val == $minCount){
delete map[key];
}
});
$minCount++;
}
});
//get the elements which belong in intersection
$intersect = new Array();
$.each(map, function(key, val){
if(val == $chars.length){
$intersect.push(parseInt(key));
}
});
return $intersect;
}

R matrix memory representation

I'm writing a plugin for R and I want to allocate a 3-dimensional R matrix to return. How can I do this? In Rinternals.h I see an allocMatrix and an alloc3DArray. Do I use one of those?
If it is too annoying, I can accept a matrix from the user, but I need to know what the internal representation is so that I can fill it in.
Thank you.
Two problems seem at issue. One is validating input from a user and the other is allocation. I would be surprised if it were very much faster to use the .Call interface or an rcpp strategy than just allocation with :
obj <- array(NA, dim=c(x,y,z)) # where the x,y and z values would be user input.
If you look at the code for array you see this as the likely workhorse function:
if (is.atomic(data) && !is.object(data))
return(.Internal(array(data, dim, dimnames)))
It's worth understanding that arrays in R are really just vectors with a dimension attribute set:
> x <- array(0, c(2, 2, 2))
> .Internal(inspect(x))
#7f859baf5ee8 14 REALSXP g0c4 [NAM(2),ATT] (len=8, tl=0) 0,0,0,0,0,...
ATTRIB:
#7f85a1d593c0 02 LISTSXP g0c0 []
TAG: #7f859c8043f8 01 SYMSXP g1c0 [MARK,LCK,gp=0x4000] "dim" (has value)
#7f85a4040bc0 13 INTSXP g0c2 [NAM(2)] (len=3, tl=0) 2,2,2
So if you want to make a matrix, or array, 'by hand', it's as simple as allocating a vector of the correct length, and then setting the dimension attribute. Eg:
SEXP myArray = PROTECT(allocVector(REALSXP, m * n * k));
SEXP myDims = PROTECT(allocVector(INTSXP, 3));
setAttrib(myArray, R_DimSymbol, myDims);

Find if one integer array is a permutation of other

Given two integer arrays of size N, design an algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.
I can think of two ways:
Sort them and compare : O(N.log N + N)
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0. This is O(N). I am not sure if this method will eliminate false positives completely. Thoughts. Better algorithms?
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0.
This doesn't work. Example:
a = [1,6] length(a) = 2, sum(a) = 7, xor(a) = 7
b = [3,4] length(b) = 2, sum(b) = 7, xor(b) = 7
Others have already suggested HashMap for an O(n) solution.
Here's an O(n) solution in C# using a Dictionary<T, int>:
bool IsPermutation<T>(IList<T> values1, IList<T> values2)
{
if (values1.Count != values2.Count)
{
return false;
}
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (T t in values1)
{
int count;
counts.TryGetValue(t, out count);
counts[t] = count + 1;
}
foreach (T t in values2)
{
int count;
if (!counts.TryGetValue(t, out count) || count == 0)
{
return false;
}
counts[t] = count - 1;
}
return true;
}
In Python you could use the Counter class:
>>> a = [1, 4, 9, 4, 6]
>>> b = [4, 6, 1, 4, 9]
>>> c = [4, 1, 9, 1, 6]
>>> d = [1, 4, 6, 9, 4]
>>> from collections import Counter
>>> Counter(a) == Counter(b)
True
>>> Counter(c) == Counter(d)
False
The best solution is probably a counting one using a map whose keys are the values in your two arrays.
Go through one array creating/incrementing the appropriate map location and go through the other one creating/decrementing the appropriate map location.
If the resulting map consists entirely of zeros, your arrays are equal.
This is O(N), and I don't think you can do better.
I suspect this is approximately what Mark Byers was going for in his answer.
If a space complexity of O(n) is not a problem, you can do it in O(n), by first storing in a hash map the number of occurrences for each value in the first array, and then running a second pass on the second array and check that every element exists in the map, decrementing the number the occurrences for each element.
Sort the contents of both arrays numerically, and then compare each nth item.
You could also take each item in array1, and then check if it is present in array2. Keep a count of how many matches you find. At the end, the number of matches should equal the length of the arrays.

Resources