I have exported matrix from Mathematica
Export["all.txt", all]
i.e.
Matrix is s.t
{{1,2,3,4},{1,2,3,4}}
I tried to import it back, but it is not usable..
Import["text.txt"]
{1, 2, 3}
{1, 2, 3}
,
Import["text.txt", "Data"]
{{"{1,", "2,", "3}"}, {"{1,", "2,", "3}"}}
or
Import["text.txt", "String"]
{1, 2, 3}
{1, 2, 3}
I cannnot use it because it is not matrix. How can I import it back as matrix? so I can get do some command like %[[1]][[1]] to obtain rows and column
There's nothing wrong with the file extension .txt, but when Mathematica exports and imports a text file, it assumes it is a string. You can see:
Export["C:\\test.txt", {{1, 2, 3}, {4, 5, 6}}]
Head[Import["C:\\test.txt"]]
(* Output: String *)
Instead, you can change the file extension as Eugene suggests:
Export["C:\\test.dat", {{1, 2, 3}, {4, 5, 6}}]
Head[Import["C:\\test.dat"]]
(* Output: List *)
Notice that it won't even use a file extension it doesn't understand:
Export["C:\\test.xyz", {{1, 2, 3}, {4, 5, 6}}]
Head[Import["C:\\test.xyz"]]
(* Output: Export::type: "List cannot be exported to the "XYZ" format." *)
Really, what's happening is Import and Export are trying to infer the type you want to use from the file extension. You can always specify that type manually instead:
Export["C:\\test.txt", {{1, 2, 3}, {4, 5, 6}},"List"]
Head[Import["C:\\test.txt"]]
(* Output: String *)
The output files for type "List" and type "String" are going to be the same, so you need to specify it when you import the file too:
Export["C:\\test.txt", {{1, 2, 3}, {4, 5, 6}},"List"]
Head[Import["C:\\test.txt","List"]]
(* Output: List *)
Note that this would work even if you forgot to Export with the type "List" specified, since the output file would still be compatible for importing as a list.
Worst case scenario, you can always try this:
Export["C:\\test.txt", {{1, 2, 3}, {4, 5, 6}}]
ToExpression[Import["C:\\test.txt"]]
(* Output: {4,5,6} *)
That doesn't quite work and only gives you bottom row. You'd have to be a bit pedantic:
Export["C:\\test.txt", {{1, 2, 3}, {4, 5, 6}}]
ToExpression[StringSplit[Import["C:\\test.txt"], "\n"]]
But of all these possibilities, the best and simplest I've mentioned is to simply tell the Import command that what you have is a list:
Import["C:\\test.txt","List"]
That's why that optional argument exists for Import in the first place. The reason it's optional is so we can be lazy and let Mathematica decide that .txt files are strings and .dat files are lists, but if you don't want Mathematica to do that (i.e. Mathematica is doing it wrong), you just specify "List" or whatever type of file you are importing.
You almost got this right but you used the type "Data" which is actually meant to indicate (from the documentation):
"data in a generic Wolfram Language form (list, string, etc.)"
which means you won't get much help there -- Mathematica will still decide this is a string. The type you want is "List".
I've noticed long time ago (since 6th versions) that Mathematica has some issues with *.txt files. Use suffix .dat. It has been proven issue-proof for me with matrices or anything.
Related
I want parse one of field in Json format its like this
"{a:[[1,2,3,4],[1,2,3,4]]}"
In the above field 'a' want to extract first two digits
I tried with List[Int] in scala its not working. Try extract first two digits in each set like this
a1:1
a2:2
"{a:[[1,2,3,4],[1,2,3,4]]}"
This is not valid JSON.
{
"a": [
[1, 2, 3, 4],
[1, 2, 3, 4]
]
}
a needs to be in double-quotes.
Edit: If this is the value of a field in Json, then it is an object with a field "a" that is a List[List[Int]].
My question is probably really easy, but I am a mathematica beginner.
I have a dataset, lets say:
Column: Numbers from 1 to 10
Column Signs
Column Other signs.
{{1,2,3,4,5,6,7,8,9,10},{d,t,4,/,g,t,w,o,p,m},{g,h,j,k,l,s,d,e,w,q}}
Now I want to extract all rows for which column 1 provides an odd number. In other words I want to create a new dataset.
I tried to work with Select and OddQ as well as with the IF function, but I have absolutely no clue how to put this orders in the right way!
Taking a stab at what you might be asking..
(table = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ,
Characters["abcdefghij"],
Characters["ABCDEFGHIJ"]}) // MatrixForm
table[[All, 1 ;; -1 ;; 2]] // MatrixForm
or perhaps this:
Select[table, OddQ[#[[1]]] &]
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}
The convention in Mathematica is the reverse of what you use in your description.
Rows are first level sublists.
Let's take your original data
mytable = {{1,2,3,4,5,6,7,8,9,10},{d,t,4,"/",g,t,w,o,p,m},{g,h,j,k,l,s,d,e,w,q}}
Just as you suggested, Select and OddQ can do what you want, but on your table, transposed. So we transpose first and back:
Transpose[Select[Transpose[mytable], OddQ[First[#]]& ]]
Another way:
Mathematica functional command MapThread can work on synchronous lists.
DeleteCases[MapThread[If[OddQ[#1], {##}] &, mytable], Null]
The inner function of MapThread gets all elements of what you call a 'row' as variables (#1, #2, etc.). So it test the first column and outputs all columns or a Null if the test fails. The enclosing DeleteCases suppresses the unmatching "rows".
CoffeeScript comes with a few helper functions. How to use them? flatten(Array) for example.
These functions seem to be intended for private use by the CoffeeScript compiler. It might be better to use a general-purpose library like Underscore.js if you want these sort of features.
coffee> _ = require('underscore')
coffee> _.flatten [1, 2, 3, [4, 5]]
[ 1, 2, 3, 4, 5 ]
This question is related to the context described in Seeking a solution or a heursitic approxmation for the 3-partition combinatorial situation. The task is distribute approximately 48 pieces of inherited jewelry, each with its appraised value, to 3 inheritors so as to give each inheritor equal or nearly equal value. That question has been sufficiently answered for my legalistic purposes.
This new question arises out of my pursuit of solving this by enumeration. Totally unnecessary legally. Just an intellectual challenge now.
The problem now:
Assign to each item a unique index: probably just the integers 1 through 48. Now allocate these 48 to each of the 3 inheritors and eliminate the duplicates.
To make this example case simpler, assert that there are only 9 items and each inheritor is to receive exactly 3 items. (Note that this diverges from the previous goal of making the 3 bins of nearly equal value.)
How to eliminate the duplications in the sequence of items-to-bins?
Example:
Let bin 1 contain items {1,2,3}
Let bin 2 contain items {4,5,6}
Let bin 3 contain items {7,8,9}
There will be 6 duplications of the final values of this triplet-of-triplets:
{1,2,3}{4,5,6}{7,8,9}
{4,5,6}{1,2,3}{7,8,9}
{4,5,6}{7,8,9}{1,2,3}
{7,8,9}{1,2,3}{4,5,6}
{7,8,9}{4,5,6}{1,2,3}
etc.
Again, how to eliminate the duplications in the sequence of items-to-bins? Without enumerating the entire set of permutations-of-triplets. No, that's not quite right. I might have to temporarily grind out all the permutations-of-triplets. How to quickly eliminate the duplicated combinations-of-triplets based on what has been done a priori?
I can imagine something like inventing a function which, given any combination of 3 items, returns a unique value. Something using prime numbers? Except that many pairs of prime numbers sum to another prime number.
I crossposted the original question on mathoverflow. I apologize for not understanding the relationship between stackoverflow and mathoverflow.
One can show that the total number of restricted partitions is
, which equals 280.
This can be reordered as:
You can get this by taking the first third of the (ordered) combinations you obtain by taking three out of nine list members and the first half of the combinations you get when you take three out of the remaining six for each choice of the first three. There's no free choice for the last three of course.
With Mathematica you might generate this as:
list = Range[9];
l1 = Subsets[list, {3}, Binomial[9, 3]/3];
l2 = Subsets[Complement[list, #], {3}, Binomial[6, 3]/2] & /# l1;
Flatten[
Outer[
Function[{ll1, ll2}, {ll1, ll2, Complement[list, ll1, ll2]}],
{#1}, #2, 1, 1
] & ### ({l1, l2}\[Transpose]),
2]
This is a good question. It is essentially a restricted set partition problem.
Here is one way in which you may approach this. I am not certain that it is optimal, but it is many magnitudes more efficient than brute force (generating all permutations and then removing duplicates).
I will be using curly brackets to represent lists, as this is familiar to me.
Start with this template, which represents zero items in three bins:
{ {{}, {}, {}} }
For each list within the outermost (i.e. just {{}, {}, {}} here):
Append 1 to each sub-list, skipping any lists that are full (contain three elements), and append only to the first empty {} list if there is more than one.
Keep a copy of the entire list for each replacement that is made, and join these together at the end of the step.
This process will then be repeated for 2, 3, etc., until all items are in bins or all bins are full. Example steps:
{ {{}, {}, {}} }
{ {{1}, {}, {}} }
{ {{1, 2}, {}, {}}, {{1}, {2}, {}} }
{ {{1, 2, 3}, {}, {}}, {{1, 2}, {3}, {}}, {{1, 3}, {2}, {}}, {{1}, {2, 3}, {}}, {{1}, {2}, {3}} }
{ {{1, 2, 3}, {4}, {}}, {{1, 2, 4}, {3}, {}}, {{1, 2}, {3, 4}, {}}, {{1, 2}, {3}, {4}}, {{1, 3, 4}, {2}, {}}, {{1, 3}, {2, 4}, {}}, {{1, 3}, {2}, {4}}, {{1, 4}, {2, 3}, {}}, {{1}, {2, 3, 4}, {}}, {{1}, {2, 3}, {4}}, {{1, 4}, {2}, {3}}, {{1}, {2, 4}, {3}}, {{1}, {2}, {3, 4}} }
Please Consider :
Subsets[Flatten[ParallelTable[{i, j}, {i, 1, 96}, {j, 1, 4}], 1], {4}]
I need to select all the Sublist such that the the i value is never the same within each sublist of 4
{{3,1},{4,1},{5,1},{6,1}} should be accepted while {{1,1},{1,2},{2,3},{6,1}} should be rejected. The Value 1 for i being repeated 2 times.
I know I could do this with Cases, but don`t understand the Syntax of it, and find the help on Cases rather empty compared to its potential applications.
Assuming your data is in the variable data, the following should do it:
Select[data, Length#Union[#[[All, 1]]] === 4 &]
This takes the "i"-value (i.e. first element), and checks that the 4 values are all different (i.e. if we remove the duplicates we still have 4 of them)
This response assumes that the input data is a list of tuples of four pairs each, e.g.:
$data = {{{3, 1}, {4, 1}, {5, 1}, {6, 1}} , {{1, 1}, {1, 2}, {2, 3}, {6, 1}}};
Using Cases, one could name and compare the first elements of each pair to ensure that they are unequal:
Cases[
$data
, {{a_, _}, {b_, _}, {c_, _}, {d_, _}} /; Unequal[a, b, c, d]
]
Another use of Cases compares the first elements of each pair without naming them:
Cases[
$data
, tuple_ /; Unequal ## tuple[[All, 1]]
]
Alternatively, one could use DeleteCases and exclude tuples with at least two pairs with the same initial value:
DeleteCases[
$data
, {___, {a_, _}, ___, {a_, _}, ___}
]
One might think that this last expression could be:
(* warning: does not work *)
Cases[$data, Except[{___, {a_, _}, ___, {a_, _}, ___}]]
... but Except does not permit named patterns in the first argument.
WReach already covered Cases well, so here is another approach.
Pick[data, Signature /# data[[All, All, 1]], 1 | -1]
It is faster than most of the other methods, but still not as fast as the fixed-length Cases method.