Build an Octave struct by "rows" - struct

I mean to use a struct to hold a "table":
% Sample data
% idx idxstr var1 var2 var3
% 1 i01 3.5 21.0 5
% 12 i12 6.5 1.0 3
The first row contains the field names.
I could enter these data by columns directly,
ds2 = struct( ...
'idx', { 1, 12 }, ...
'idxstr', { 'i01', 'i12' }, ...
'var1', { 3.5, 6.5 }, ...
'var2', { 21, 1 }, ...
'var3', { 5, 3 } ...
);
and by rows indirectly, creating a cell array, and converting to struct,
ds3 = cell2struct( ...
{ 1, 'i01', 3.5, 21.0, 5; ...
12, 'i12', 6.5, 1.0, 3 ...
}, { 'idx', 'idxstr', 'var1', 'var2', 'var3' }, 2 );
Is there a direct way to enter data by rows?
In addition,
why the different sizes?
>> size(ds2), size(ds3)
ans =
1 2
ans =
2 1

As I mentioned in your other post here, you are probably better off creating your 'table' as a struct of array fields, rather than an array of single-row structs.
However, for the sake of writing a useful answer, I will assume the reason you opted for this form to begin with may be that you already have your data as rows in 'cell' form (e.g. possibly the output of a csv2cell operation), and you'd like to convert it to such a "table".
Therefore, to create a nice "table as struct of arrays" from such a data structure, you could follow a strategy like the following:
Data = { 1, 'i01', 3.5, 21.0, 5; 12, 'i12', 6.5, 1.0, 3 };
d1 = struct( 'idx' , [Data{:,1}] ,
'idxstr', {{Data{:,2}}}, % note the 'enclosing' braces!
'var1' , [Data{:,3}] ,
'var2' , [Data{:,4}] ,
'var3' , [Data{:,5}]
);
or, using cell2struct if you prefer that syntax:
d2 = cell2struct( { [Data{:,1}],
{Data{:,2}}, % note the lack of enclosing braces here!
[Data{:,3}],
[Data{:,4}],
[Data{:,5}] },
{ 'idx', 'idxstr', 'var1', 'var2', 'var3' },
2
);
Note that you "do" need to know if a 'column' represents a numeric or string array, so that you wrap it in [] or {} respectively ... but I think knowing the data-type represented by each column is not an unreasonable requirement from a programmer.

Related

Transpose CSV data using nodejs

"A",1,2,3,4
"B",1,2,3,4
"C",1,2,3,4
I want to transpose and get the output as
"A""B""C"
111
222
333
444
Hi sai kiran bandari !
Please provide more information for your next question.
I expect you to have a 2 dimension array for which i made a solution. You want to iteratoe through the array using 2 loops and split the values to a new 2 dimension array according to first array index i in this case.
const data =[['A', 1,2,3,4], ['B', 1,2,3,4], ['C', 1,2,3,4]]
const transposed = []
// iterate through 2 dimension array..
for(var i = 0; i < data.length; i++) {
var arr = data[i]
// Iterate through inner araray
for(let p = 0; p < arr.length; p++) {
// create new inner array if there is not already one at destination..
if(Array.isArray(transposed[p]) === false) {
transposed[p] = []
}
// we want to take all the values of the first array and split it
// up to a single array each. In the second iteration, alle the
// values will be splitted again and you have your transpose.
transposed[p].push(arr[p])
}
}
console.log(transposed)
/* Output => [
[ 'A', 'B', 'C' ],
[ 1, 1, 1 ],
[ 2, 2, 2 ],
[ 3, 3, 3 ],
[ 4, 4, 4 ]
]
*/

Simplified way to add up integer values from a JSON [duplicate]

This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 2 years ago.
I have the following data structure
{
metadata: {
a: 0,
b: 4,
c: 1,
d: 6
}
}
I want to find a simple way to add all the variables in the metadata together without having to do them one at a time.. like metadata.a + metadata.b + metadata.c + metadata.d
I am hoping for a way to just add whatever variable exists in that
Any suggestions?
Simplified using ES6
const data = {
metadata: {
a: 0,
b: 4,
c: 1,
d: 6
}
}
const sum = Object.entries(data.metadata).reduce((sum, x) => sum+ x[1], 0)
console.log(sum)
You can use a simple for ... in loop for that
const metadata = {
a: 0,
b: 4,
c: 1,
d: 6
}
let sum = 0
for (let key in metadata) {
sum += metadata[key]
}
console.log(sum)

Groovy #Memoize expiry based on custom event

I am using groovy to process a batch job, I am planning to cache domain object by using groovy's #Memoize annotation, but problem is the expiry, I want to expire the cache when the job is finished. Is there any way to tell groovy to expire the cache from code?
As per the docs, #Memoized features only a max value and a protection cache size parameters.
Since the AST under the covers will create the memoize mechanism through Closure::memoize, you could emulate it with a map and memoized closures which can be disposed:
class Job {
def log = []
def repoBase = [
sum: { a, b ->
log << "sum $a and $b"
a + b
},
multiply: { a, b ->
log << "multiply $a and $b"
}
]
def repo
def startJob() {
repo = repoBase.collectEntries { key, value ->
[(key): value.memoize()]
} as Expando
}
def withJob(Closure c) {
startJob()
c.delegate = repo
c.delegateStrategy = Closure.DELEGATE_FIRST
c(this)
repo = null
}
}
And test:
j = new Job()
j.withJob {
multiply 3, 4
multiply 3, 4
multiply 8, 8
sum 9, 9
sum 1, 2
sum 9, 9
}
assert j.log == [
"multiply 3 and 4",
"multiply 8 and 8",
"sum 9 and 9",
"sum 1 and 2"
]

Reorder string characters in Swift

So, let's say I have a String that is: "abc" and I want to change each character position so that I can have "cab" and later "bca". I want the character at index 0 to move to 1, the one on index 1 to move to 2 and the one in index 2 to 0.
What do I have in Swift to do this? Also, let's say instead of letters I had numbers. Is there any easier way to do it with integers?
Swift 2:
extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
mutating func cycleAround() {
insert(removeLast(&self), atIndex: startIndex)
}
}
var ar = [1, 2, 3, 4]
ar.cycleAround() // [4, 1, 2, 3]
var letts = "abc".characters
letts.cycleAround()
String(letts) // "cab"
Swift 1:
func cycleAround<C : RangeReplaceableCollectionType where C.Index : BidirectionalIndexType>(inout col: C) {
col.insert(removeLast(&col), atIndex: col.startIndex)
}
var word = "abc"
cycleAround(&word) // "cab"
In the Swift Algorithms package there is a rotate command
import Algorithms
let string = "abcde"
var stringArray = Array(string)
for _ in 0..<stringArray.count {
stringArray.rotate(toStartAt: 1)
print(String(stringArray))
}
Result:
bcdea
cdeab
deabc
eabcd
abcde

In Groovy, how do I add up the values for a certain property in a map?

I have the following map:
def map = [];
map.add([ item: "Shampoo", count: 5 ])
map.add([ item: "Soap", count: 3 ])
I would like to get the sum of all the count properties in the map. In C# using LINQ, it would be something like:
map.Sum(x => x.count)
How do I do the same in Groovy?
Assuming you have a list like so:
List list = [ [item: "foo", count: 5],
[item: "bar", count: 3] ]
Then there are multiple ways of doing it. The most readable is probably
int a = list.count.sum()
Or you could use the Closure form of sum on the whole list
int b = list.sum { it.count }
Or you could even use a more complex route such as inject
int c = list.count.inject { tot, ele -> tot + ele } // Groovy 2.0
// c = list.count.inject( 0 ) { tot, ele -> tot + ele } // Groovy < 2.0
All of these give the same result.
assert ( a == b ) && ( b == c ) && ( c == 8 )
I would use the first one.
You want to use the collect operator. I checked the following code with groovysh:
list1 = []
total = 0
list1[0] = [item: "foo", count: 5]
list1[1] = [item: "bar", count: 3]
list1.collect{ total += it.count }
println "total = ${total}"
First of all, you're confusing map and list syntax in your example. Anyhow, Groovy injects a .sum(closure) method to all collections.
Example:
[[a:1,b:2], [a:5,b:4]].sum { it.a }
===> 6

Resources