What regex pattern matches this string? - regex

Been scratching my head on this for hours to no avail! I need to match 3 different parts of this string, in 3 different patterns. So one regex pattern matches the first, etc.
Here is the string:
{
"jsonrpc": "2.0",
"result": [
{
"marketId": "1.123485047",
"isMarketDataDelayed": false,
"status": "OPEN",
"betDelay": 0,
"bspReconciled": false,
"complete": true,
"inplay": false,
"numberOfWinners": 1,
"numberOfRunners": 3,
"numberOfActiveRunners": 3,
"lastMatchTime": "2016-03-18T23:21:14.211Z",
"totalMatched": 47663.09,
"totalAvailable": 140527.57,
"crossMatching": true,
"runnersVoidable": false,
"version": 1259153627,
"runners": [
{
"selectionId": 48224,
"handicap": 0.0,
"status": "ACTIVE",
"lastPriceTraded": 1.57,
"totalMatched": 37408.96,
"ex": {
"availableToBack": [
{
"price": 1.56,
"size": 1344.78
},
{
"price": 1.55,
"size": 642.45
},
{
"price": 1.54,
"size": 1034.4
}
],
"availableToLay": [
{
"price": 1.57,
"size": 303.34
},
{
"price": 1.58,
"size": 2368.34
},
{
"price": 1.59,
"size": 1220.99
}
],
"tradedVolume": []
}
},
{
"selectionId": 1141,
"handicap": 0.0,
"status": "ACTIVE",
"lastPriceTraded": 7.0,
"totalMatched": 5863.62,
"ex": {
"availableToBack": [
{
"price": 7.0,
"size": 286.85
},
{
"price": 6.8,
"size": 552.02
},
{
"price": 6.6,
"size": 25.81
}
],
"availableToLay": [
{
"price": 7.2,
"size": 36.05
},
{
"price": 7.4,
"size": 312.79
},
{
"price": 7.6,
"size": 92.63
}
],
"tradedVolume": []
}
},
{
"selectionId": 58805,
"handicap": 0.0,
"status": "ACTIVE",
"lastPriceTraded": 4.5,
"totalMatched": 4390.5,
"ex": {
"availableToBack": [
{
"price": 4.5,
"size": 209.65
},
{
"price": 4.4,
"size": 692.37
},
{
"price": 4.3,
"size": 429.69
}
],
"availableToLay": [
{
"price": 4.6,
"size": 279.02
},
{
"price": 4.7,
"size": 821.2
},
{
"price": 4.8,
"size": 928.88
}
],
"tradedVolume": []
}
}
]
}
],
"id": 1
}
I bolded the 3 parts which need extracting. (in this case they are 1.57, 7.2 and 4.6). These numbers can be integers, have 1 or 2 decimals.

One possible regex to extract 1.57, 7.2 and 4.6 would be :
(?:availableToLay[^\d]+)([\d.]+)
https://regex101.com/r/vP5iH2/1

UPDATE: Just seen the answer from "florentbr" and that is a much tidier answer than mine!
Do you really need RegEx? There's probably many ways of doing this, but breaking down by commas seems to hit the right data. Open up Excel, and dump your data in Cell "A1", then past this code into the VBA editor:
Option Explicit
Sub getYourVals()
Dim dataStr() As String
Dim i As Integer
Dim marker As String
marker = "availableToLay"
dataStr = Split(Range("A" & 1).Value, ",")
For i = 1 To UBound(dataStr)
If Mid(dataStr(i), 2, Len(marker)) = marker Then
Debug.Print Mid(dataStr(i), 28, Len(dataStr(i)) - 27)
End If
Range("A" & i + 1).Value = dataStr(i)
Next i
End Sub

Consider parsing the JSON string altogether, flattening it for needed data. JSON formats can be thought of as an assembly of dictionaries and collections, two data structures VBA maintains. Below uses VBA Tools' VBA-JSON library.
Setup Steps
Import the .bas file in above link into a VBA module in IDE.
Add the VBA Reference for Microsoft Scripting Runtime
VBA Script (loops through the results, runners, and ex collections)
Sub JSONStringData()
Dim jsonStr As String
Dim element As Variant, e As Variant, n As Variant, r As Variant
Dim x As Variant, s As Variant, pr As Variant, dat As Variant
Dim i As Integer, num As Integer
jsonStr = "{""jsonrpc"":""2.0"",""result"":" _
& "[{""marketId"":""1.123485047"",""isMarketDataDelayed"":false,""status"":""OPEN""," _
& """betDelay"":0,""bspReconciled"":false,""complete"":true,""inplay"":false," _
& """numberOfWinners"":1,""numberOfRunners"":3,""numberOfActiveRunners"":3,""lastMatchTime"":" _
& """2016-03-18T23:21:14.211Z"",""totalMatched"":47663.09,""totalAvailable"":140527.57,""crossMatching"":true," _
& """runnersVoidable"":false,""version"":1259153627,""runners"":" _
& "[{""selectionId"":48224,""handicap"":0.0,""status"":""ACTIVE"",""lastPriceTraded"":1.57," _
& """totalMatched"":37408.96,""ex"":{""availableToBack"":[{""price"":1.56,""size"":1344.78}," _
& "{""price"":1.55,""size"":642.45},{""price"":1.54,""size"":1034.4}],""availableToLay"":" _
& "[{""price"":1.57,""size"":303.34},{""price"":1.58,""size"":2368.34},{""price"":1.59,""size"":1220.99}]," _
& """tradedVolume"":[]}},{""selectionId"":1141,""handicap"":0.0,""status"":""ACTIVE""," _
& """lastPriceTraded"":7.0,""totalMatched"":5863.62,""ex"":{""availableToBack"":[{""price"":7.0," _
& """size"":286.85},{""price"":6.8,""size"":552.02},{""price"":6.6,""size"":25.81}],""availableToLay"":" _
& "[{""price"":7.2,""size"":36.05},{""price"":7.4,""size"":312.79},{""price"":7.6,""size"":" _
& "92.63}],""tradedVolume"":[]}},{""selectionId"":58805,""handicap"":0.0,""status"":" _
& """ACTIVE"",""lastPriceTraded"":4.5,""totalMatched"":4390.5,""ex"":{""availableToBack"":" _
& "[{""price"":4.5,""size"":209.65},{""price"":4.4,""size"":692.37},{""price"":4.3,""size"":429.69}]" _
& ",""availableToLay"":[{""price"":4.6,""size"":279.02},{""price"":4.7,""size"":821.2}," _
& "{""price"":4.8,""size"":928.88}],""tradedVolume"":[]}}]}],""id"":1}"
' PARSE FILE STRING
Dim p As Object
Set p = ParseJson(jsonStr)
i = 5
For Each element In p
' RESULT COLLECTION OF DICTIONARIES (N = 17)
If element = "result" Then
For Each e In p(element)
For Each n In e
' RUNNERS COLLECTION OF DICTIONARIES (N = 6)
If n = "runners" Then
For Each r In e(n)
For Each x In r
' EX DICTIONARY OF COLLECTIONS (N = 9, 3 PER 3 RUNNERS)
If x = "ex" Then
For Each s In r(x)
num = 1
For Each pr In r(x)(s)
For Each dat In pr
Sheets(1).Range("A" & i) = r("selectionId")
Sheets(1).Range("B" & i) = r("handicap")
Sheets(1).Range("C" & i) = r("status")
Sheets(1).Range("D" & i) = r("lastPriceTraded")
Sheets(1).Range("E" & i) = r("totalMatched")
Sheets(1).Range("F" & i) = s
Sheets(1).Range("G" & i) = num
Sheets(1).Range("H" & i) = dat
Sheets(1).Range("I" & i) = pr(dat)
i = i + 1
Next dat
num = num + 1
Next pr
Next s
End If
Next x
Next r
End If
Next n
Next e
End If
Next element
End Sub
Result (where 1.57, 7.2, and 4.6 are the first prices for availableToLay for each of three runners)
48224 0 ACTIVE 1.57 37408.96 availableToBack 1 price 1.56
48224 0 ACTIVE 1.57 37408.96 availableToBack 1 size 1344.78
48224 0 ACTIVE 1.57 37408.96 availableToBack 2 price 1.55
48224 0 ACTIVE 1.57 37408.96 availableToBack 2 size 642.45
48224 0 ACTIVE 1.57 37408.96 availableToBack 3 price 1.54
48224 0 ACTIVE 1.57 37408.96 availableToBack 3 size 1034.4
48224 0 ACTIVE 1.57 37408.96 availableToLay 1 price 1.57
48224 0 ACTIVE 1.57 37408.96 availableToLay 1 size 303.34
48224 0 ACTIVE 1.57 37408.96 availableToLay 2 price 1.58
48224 0 ACTIVE 1.57 37408.96 availableToLay 2 size 2368.34
48224 0 ACTIVE 1.57 37408.96 availableToLay 3 price 1.59
48224 0 ACTIVE 1.57 37408.96 availableToLay 3 size 1220.99
1141 0 ACTIVE 7 5863.62 availableToBack 1 price 7
1141 0 ACTIVE 7 5863.62 availableToBack 1 size 286.85
1141 0 ACTIVE 7 5863.62 availableToBack 2 price 6.8
1141 0 ACTIVE 7 5863.62 availableToBack 2 size 552.02
1141 0 ACTIVE 7 5863.62 availableToBack 3 price 6.6
1141 0 ACTIVE 7 5863.62 availableToBack 3 size 25.81
1141 0 ACTIVE 7 5863.62 availableToLay 1 price 7.2
1141 0 ACTIVE 7 5863.62 availableToLay 1 size 36.05
1141 0 ACTIVE 7 5863.62 availableToLay 2 price 7.4
1141 0 ACTIVE 7 5863.62 availableToLay 2 size 312.79
1141 0 ACTIVE 7 5863.62 availableToLay 3 price 7.6
1141 0 ACTIVE 7 5863.62 availableToLay 3 size 92.63
58805 0 ACTIVE 4.5 4390.5 availableToBack 1 price 4.5
58805 0 ACTIVE 4.5 4390.5 availableToBack 1 size 209.65
58805 0 ACTIVE 4.5 4390.5 availableToBack 2 price 4.4
58805 0 ACTIVE 4.5 4390.5 availableToBack 2 size 692.37
58805 0 ACTIVE 4.5 4390.5 availableToBack 3 price 4.3
58805 0 ACTIVE 4.5 4390.5 availableToBack 3 size 429.69
58805 0 ACTIVE 4.5 4390.5 availableToLay 1 price 4.6
58805 0 ACTIVE 4.5 4390.5 availableToLay 1 size 279.02
58805 0 ACTIVE 4.5 4390.5 availableToLay 2 price 4.7
58805 0 ACTIVE 4.5 4390.5 availableToLay 2 size 821.2
58805 0 ACTIVE 4.5 4390.5 availableToLay 3 price 4.8
58805 0 ACTIVE 4.5 4390.5 availableToLay 3 size 928.88

Related

Reproduce list of data frame

today I wanted to run TropFishR package, the problem is (to me), every data must be arranged in list. So I tried to reconstruct the alba dataset in order to replicate with my own data in the future. Here is what I have done:
library(TropFishR)
data("alba")
str(alba) #the list contain 4 variables
List of 4
$ sample.no : int [1:14] 1 2 3 4 5 6 7 8 9 10 ...
$ midLengths: num [1:14] 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 ...
$ dates : Date[1:7], format: "1976-04-17" "1976-07-02" "1976-09-19" ...
$ catch : num [1:14, 1:7] 0 0 0 1 1 1 3 9 5 0 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : NULL
.. ..$ : chr [1:7] "1976.29315068493" "1976.50136986301" "1976.71780821918" "1976.95616438356" ...
- attr(*, "class")= chr "lfq"
And this is what I did:
#1 We create sample.no
sample.no <- c(1:14)
sample.no
#2 We create "midlengths"
midlengths <- seq(from = 1.5, to = 14.5, by = 1)
midlengths
#3 We create "dates"
dates <- as.Date(c("1976-04-17","1976-07-02", "1976-09-19", "1976-12-15", "1977-02-18",
"1977-04-30", "1977-06-24"))
dates
#4 We create "catch"
catch <- as.matrix(read.csv(file.choose(), header=T))
#I copied the alba length freq data, move it to excel and imported as csv file
colnames(catch)<-NULL
print(catch)
#5 create list files
synLFQb <- list(sample.no,midlengths,dates,catch)
synLFQb #just checked if it turned out to be as desired format
#6 create a name for the data list
names(synLFQb) <- c("sample.no","midlengths","dates","catch")
#Finally, we need to assign the class lfq to our new object in order to allow it to be recognized by other TropFishR functions, e.g. plot.lfq:
class(synLFQb) <- "lfq"
it will produce "similar" data list
str(synLFQb)
List of 4
$ sample.no : int [1:14] 1 2 3 4 5 6 7 8 9 10 ...
$ midlengths: num [1:14] 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 ...
$ dates : Date[1:7], format: "1976-04-17" "1976-07-02" "1976-09-19" ...
$ catch : int [1:14, 1:7] 0 0 0 1 1 1 3 9 5 0 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : NULL
.. ..$ : NULL
- attr(*, "class")= chr "lfq"
However, when everytime I tried to do this simple command:
plot(synLFQb, Fname="catch", hist.sc = 1)
It resulted in error:
> plot(synLFQb, Fname="catch", hist.sc = 1)
Error in plot.window(...) : need finite 'ylim' values
In addition: Warning messages:
1: In min(x, na.rm = na.rm) :
no non-missing arguments to min; returning Inf
2: In max(x, na.rm = na.rm) :
no non-missing arguments to max; returning -Inf
Any help will be much appreciated.
Please make sure that you call the mid lengths vector in your list "midLengths" with a capital "L". I hope that will does the trick in your example.

for loop in pandas to search dataframe and update list stuck

I want to count areas of interest in my dataframe column 'which_AOI' (ranging from 0 -9). I would like to have a new column with the results added to a dataframe depending on a variable 'marker' (ranging from 0 - x) which tells me when one 'picture' is done and the next begins (one marker can go on for a variable length of rows). This is my code so far but it seems to be stuck and runs on without giving output. I tried reconstructing it from the beginning once but as soon as i get to 'if df.marker == num' it doesn't stop. What am I missing?
(example dataframe below)
## AOI count of spec. type function (in progress):
import numpy as np
import pandas as pd
path_i = "/Users/Desktop/Pilot/results/gazedata_filename.csv"
df = pd.read_csv(path_i, sep =",")
#create a new dataframe for AOIs:
d = {'marker': []}
df_aoi = pd.DataFrame(data=d)
### Creating an Aoi list
item = df.which_AOI
aoi = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #list for search
aoi_array = [0, 0 , 0, 0, 0, 0, 0, 0, 0, 0] #list for filling
num = 0
for i in range (0, len (df.marker)): #loop through the dataframe
if df.marker == num: ## if marker = num its one picture
for index, item in enumerate(aoi): #look for item (being a number in which_AOI) in aoi list
if (item == aoi[index]):
aoi_array[index] += 1
print (aoi)
print (aoi_array)
se = pd.Series(aoi_array) # make list into a series to attach to dataframe
df_aoi['new_col'] = se.values #add list to dataframe
aoi_array.clear() #clears list before next picture
else:
num +=1
index pos_time pos_x pos_y pup_time pup_diameter marker which_AOI fixation Picname shock
1 16300 168.608779907227 -136.360855102539 16300 2.935715675354 0 7 18 5 save
2 16318 144.97673034668 -157.495513916016 16318 3.08838820457459 0 8 33 5 save
3 16351 152.92560577392598 -156.64172363281298 16351 3.0895299911499 0 7 17 5 save
4 16368 152.132453918457 -157.989685058594 16368 3.111008644104 0 7 18 5 save
5 16386 151.59835815429702 -157.55587768554702 16386 3.09514689445496 0 7 18 5 save
6 16404 150.88092803955098 -152.69479370117202 16404 3.10009074211121 1 7 37 5 save
7 16441 152.76554107666 -142.06188964843798 16441 3.0821495056152304 1 7 33 5 save
Not 100% clear based on your question but it sounds like you want to count the number of rows for each which_AOI value in each marker.
You can accomplish this using groupby
df_aoi = df.groupby(['marker','which_AOI']).size().unstack('which_AOI',fill_value=0)
In:
pos_time pos_x pos_y pup_time pup_diameter marker \
0 16300 168.608780 -136.360855 16300 2.935716 0
1 16318 144.976730 -157.495514 16318 3.088388 0
2 16351 152.925606 -156.641724 16351 3.089530 0
3 16368 152.132454 -157.989685 16368 3.111009 0
4 16386 151.598358 -157.555878 16386 3.095147 0
5 16404 150.880928 -152.694794 16404 3.100091 1
6 16441 152.765541 -142.061890 16441 3.082150 1
which_AOI fixation Picname shock
0 7 18 5 save
1 8 33 5 save
2 7 17 5 save
3 7 18 5 save
4 7 18 5 save
5 7 37 5 save
6 7 33 5 save
Out:
which_AOI 7 8
marker
0 4 1
1 2 0

Transform a list to a list of average values (by step)

I have a two dimensional list of values:
[
[[12.2],[5325]],
[[13.4],[235326]],
[[15.9],[235326]],
[[17.7],[53521]],
[[21.3],[42342]],
[[22.6],[6546]],
[[25.9],[34634]],
[[27.2],[523523]],
[[33.4],[235325]],
[[36.2],[235352]]
]
I would like to get a list of averages defined by a given step so that for a step=10 it would like like this:
[
[[10],[average of all 10-19]],
[[20],[average of all 20-29]],
[[30],[average of all 30-39]]
]
How can I achieve that? Please note that the number of 10s, 20s, 30s and so on is not always the same.
import pandas as pd
df = pd.DataFrame((q[0][0], q[1][0]) for q in thelist)
df['group'] = (df[0] / 10).astype(int)
Now df is:
0 1 group
0 12.2 5325 1
1 13.4 235326 1
2 15.9 235326 1
3 17.7 53521 1
4 21.3 42342 2
5 22.6 6546 2
6 25.9 34634 2
7 27.2 523523 2
8 33.4 235325 3
9 36.2 235352 3
Then:
df.groupby('group').mean()
Gives you the answers you seek:
0 1
group
1 14.80 132374
2 24.25 151761
3 34.80 235338

Which pattern occurs the most in a matrix - R (UPDATE)

UPDATE 2
*I've added some code (and explanation) I wrote myself at the end of this question, this is however a suboptimal solution (both in coding efficiency as resulting output) but kind of manages to make a selection of items that adhere to the constraints. If you have any ideas on how to improve it (again both in efficiency as resulting output) please let me know.
1. Updated Post
Please look below for the initial question and sample code. Thx to alexis_laz his answer the problem was solved for a small number of items. However when the number of items becomes to large the combn function in R cannot calculate it anymore because of the invalid 'ncol' value (too large or NA) error. Since my dataset has indeed a lot of items, I was wondering whether replacing some of his code (shown after this) with C++ provides a solution to this, and if this is the case what code I should use for this? Tnx!
This is the code as provided by alexis_laz;
ff = function(x, No_items, No_persons)
{
do.call(rbind,
lapply(No_items:ncol(x),
function(n) {
col_combs = combn(seq_len(ncol(x)), n, simplify = F)
persons = lapply(col_combs, function(j) rownames(x)[rowSums(x[, j, drop = F]) == n])
keep = unlist(lapply(persons, function(z) length(z) >= No_persons))
data.frame(persons = unlist(lapply(persons[keep], paste, collapse = ", ")),
items = unlist(lapply(col_combs[keep], function(z) paste(colnames(x)[z], collapse = ", "))))
}))
}
2. Initial Post
Currently I'm working on a set of data coming from adaptive measurement, which means that not all persons have made all of the same items. For my analysis however I need a dataset that contains only items that have been made by all persons (or a subset of these persons).
I have a matrix object in R with rows = persons (100000), and columns = items(220), and a 1 in a cell if the person has made the item and a 0 if the person has not made the item.
How can I use R to determine which combination of at least 15 items, is made by the highest amount of persons?
Hopefully the question is clear (if not please ask me for more details and I will gladly provide those).
Tnx in advance.
Joost
Edit:
Below is a sample matrix with the items (A:E) as columns and persons (1:5) as rows.
mat <- matrix(c(1,1,1,0,0,1,1,0,1,1,1,1,1,0,1,0,1,1,0,0,1,1,1,1,0),5,5,byrow=T)
colnames(mat) <- c("A","B","C","D","E")
rownames(mat) <- 1:5
> mat
A B C D E
"1" 1 1 1 0 0
"2" 1 1 0 1 1
"3" 1 1 1 0 1
"4" 0 1 1 0 0
"5" 1 1 1 1 0
mat[1,1] = 1 means that person 1 has given a response to item 1.
Now (in this example) I'm interested in finding out which set of at least 3 items is made by at least 3 people. So here I can just go through all possible combinations of 3, 4 and 5 items to check how many people have a 1 in the matrix for each item in a combination.
This will result in me choosing the item combination A, B and C, since it is the only combination of items that has been made by 3 people (namely persons 1, 3 and 5).
Now for my real dataset I want to do this but then for a combination of at least 10 items that a group of at least 75 people all responded to. And since I have a lot of data preferably not by hand as in the example data.
I'm thus looking for a function/code in R, that will let me select the minimal amount of items, and questions, and than gives me all combinations of items and persons that adhere to these constraints or have a greater number of items/persons than the constrained.
Thus for the example matrix it would be something like;
f <- function(data,no.items,no.persons){
#code
}
> f(mat,3,3)
no.item no.pers items persons
1 3 3 A, B, C 1, 3, 5
Or in case of at least 2 items that are made by at least 3 persons;
> f(mat,2,3)
no.item no.pers items persons
1 2 4 A, B 1, 2, 3, 5
2 2 3 A, C 1, 3, 5
3 2 4 B, C 1, 3, 4, 5
4 3 3 A, B, C 1, 3, 5
Hopefully this clears up what my question actually is about. Tnx for the quick replies that I already received!
3. Written Code
Below is the code I've written today. It takes each item once as a starting point and then looks to the item that has been answered most by people who also responded to the start item. It the takes these two items and looks to a third item, and repeats this until the number of people that responded to all selected questions drops below the given limit. One drawback of the code is that it takes some time to run, (it goes up somewhat exponentially when the number of items grows). The second drawback is that this still does not evaluate all possible combinations of items, in the sense that the start item, and the subsequently chosen item may have a lot of persons that answered to these items in common, however if the chosen item has almost no similarities with the other (not yet chosen) items, the sample might shrink very fast. While if an item was chosen with somewhat less persons in common with the start item, and this item has a lot of connections to other items, the final collection of selected items might be much bigger than the one based on the code used below. So again suggestions and improvements in both directions are welcome!
set.seed(512)
mat <- matrix(rbinom(1000000, 1, .6), 10000, 100)
colnames(mat) <- 1:100
fff <- function(data,persons,items){
xx <- list()
for(j in 1:ncol(data)){
d <- matrix(c(j,length(which(data[,j]==1))),1,2)
colnames(d) <- c("item","n")
t = persons+1
a <- j
while(t >= persons){
b <- numeric(0)
for(i in 1:ncol(data)){
z <- c(a,i)
if(i %in% a){
b[i] = 0
} else {
b[i] <- length(which(rowSums(data[,z])==length(z)))
}
}
c <- c(which.max(b),max(b))
d <- rbind(d,c)
a <- c(a,c[1])
t <- max(b)
}
print(j)
xx[[j]] = d
}
x <- y <- z <- numeric(0)
zz <- matrix(c(0,0,rep(NA,ncol(data))),length(xx),ncol(data)+2,byrow=T)
colnames(zz) <- c("n.pers", "n.item", rep("I",ncol(data)))
for(i in 1:length(xx)){
zz[i,1] <- xx[[i]][nrow(xx[[i]])-1,2]
zz[i,2] <- length(unname(xx[[i]][1:nrow(xx[[i]])-1,1]))
zz[i,3:(zz[i,2]+2)] <- unname(xx[[i]][1:nrow(xx[[i]])-1,1])
}
zz <- zz[,colSums(is.na(zz))<nrow(zz)]
zz <- zz[which((rowSums(zz,na.rm=T)/rowMeans(zz,na.rm=T))-2>=items),]
zz <- as.data.frame(zz)
return(zz)
}
fff(mat,110,8)
> head(zz)
n.pers n.item I I I I I I I I I I
1 156 9 1 41 13 80 58 15 91 12 39 NA
2 160 9 2 27 59 13 81 16 15 6 92 NA
3 158 9 3 59 83 32 25 80 14 41 16 NA
4 160 9 4 24 27 71 32 10 63 42 51 NA
5 114 10 5 59 66 27 47 13 44 63 30 52
6 158 9 6 13 56 61 12 59 8 45 81 NA
#col 1 = number of persons in sample
#col 2 = number of items in sample
#col 3:12 = which items create this sample (NA if n.item is less than 10)
to follow up on my comment, something like:
set.seed(1618)
mat <- matrix(rbinom(1000, 1, .6), 100, 10)
colnames(mat) <- sample(LETTERS, 10)
rownames(mat) <- sprintf('person%s', 1:100)
mat1 <- mat[rowSums(mat) > 5, ]
head(mat1)
# A S X D R E Z K P C
# person1 1 1 1 0 1 1 1 1 1 1
# person3 1 0 1 1 0 1 0 0 1 1
# person4 1 0 1 1 1 1 1 0 1 1
# person5 1 1 1 1 1 0 1 1 0 0
# person6 1 1 1 1 0 1 0 1 1 0
# person7 0 1 1 1 1 1 1 1 0 0
table(rowSums(mat1))
# 6 7 8 9
# 24 23 21 5
tab <- table(sapply(1:nrow(mat1), function(x)
paste(names(mat1[x, ][mat1[x, ] == 1]), collapse = ',')))
data.frame(tab[tab > 1])
# tab.tab...1.
# A,S,X,D,R,E,P,C 2
# A,S,X,D,R,E,Z,P,C 2
# A,S,X,R,E,Z,K,C 3
# A,S,X,R,E,Z,P,C 2
# A,S,X,Z,K,P,C 2
Here is another idea that matches your output:
ff = function(x, No_items, No_persons)
{
do.call(rbind,
lapply(No_items:ncol(x),
function(n) {
col_combs = combn(seq_len(ncol(x)), n, simplify = F)
persons = lapply(col_combs, function(j) rownames(x)[rowSums(x[, j, drop = F]) == n])
keep = unlist(lapply(persons, function(z) length(z) >= No_persons))
data.frame(persons = unlist(lapply(persons[keep], paste, collapse = ", ")),
items = unlist(lapply(col_combs[keep], function(z) paste(colnames(x)[z], collapse = ", "))))
}))
}
ff(mat, 3, 3)
# persons items
#1 1, 3, 5 A, B, C
ff(mat, 2, 3)
# persons items
#1 1, 2, 3, 5 A, B
#2 1, 3, 5 A, C
#3 1, 3, 4, 5 B, C
#4 1, 3, 5 A, B, C

Simulink link by tcpip with C++ application

I am tryng to build a link between my simulink model or just an m file and my C++ application but I'm having an issue. I don't really understand how matlab receives the data, and for simulink in which form should I send the data to the block? I would like to send coordinates like xyz to matlab and with matlab scatter3 the stream of coordinates in real time. Is it possible ?
Here is the C++ extract code : (sorry comments are in french)
/* Démarrage du listage (mode server) */
sock_err = listen(sock, 5);
printf("Listage du port %d...\n", PORT);
/* Si la socket fonctionne */
if(sock_err != SOCKET_ERROR)
{
/* Attente pendant laquelle le client se connecte */
printf("Patientez pendant que le client se connecte sur le port %d...\n", PORT);
csock = accept(sock, (SOCKADDR*)&csin, &recsize);
printf("Un client se connecte avec la socket %d de %s:%d\n", csock, inet_ntoa(csin.sin_addr), htons(csin.sin_port));
// double buff = 25;
mxArray *datasend;
datasend = mxCreateDoubleMatrix(1, 1, mxREAL);
mlfPrintmatrix(datasend);
sock_err = send(csock, T, 3*sizeof(double), 0);
if(sock_err != SOCKET_ERROR)
printf("Send : %s\n", buffer[0]);
//printf("send : [10 20 30]");
else
printf("Erreur de transmission\n");
/* Il ne faut pas oublier de fermer la connexion (fermée dans les deux sens) */
shutdown(csock, 2);
}
Simulink errors:
Error evaluating registered method 'Outputs' of M-S-Function 'stcpiprb' in 'trajectory2/TCP//IP Receive'. The specified amount of data was not returned within the Timeout period.
Please ensure that data is being sent to the specified port or specify a greater timeout value.
The specified amount of data was not returned within the Timeout period.
Please ensure that data is being sent to the specified port or specify a greater timeout value.
simulink model :
Model {
Name "trajectory2"
Version 7.4
MdlSubVersion 0
GraphicalInterface {
NumRootInports 0
NumRootOutports 0
ParameterArgumentNames ""
ComputedModelVersion "1.3"
NumModelReferences 0
NumTestPointedSignals 0
}
SavedCharacterEncoding "UTF-8"
SaveDefaultBlockParams on
ScopeRefreshTime 0.035000
OverrideScopeRefreshTime on
DisableAllScopes off
DataTypeOverride "UseLocalSettings"
MinMaxOverflowLogging "UseLocalSettings"
MinMaxOverflowArchiveMode "Overwrite"
MaxMDLFileLineLength 120
Created "Tue Feb 23 11:53:02 2010"
Creator "root"
UpdateHistory "UpdateHistoryNever"
ModifiedByFormat "%<Auto>"
LastModifiedBy "root"
ModifiedDateFormat "%<Auto>"
LastModifiedDate "Wed Feb 24 01:01:41 2010"
RTWModifiedTimeStamp 188862533
ModelVersionFormat "1.%<AutoIncrement:3>"
ConfigurationManager "None"
SampleTimeColors off
SampleTimeAnnotations off
LibraryLinkDisplay "none"
WideLines off
ShowLineDimensions off
ShowPortDataTypes off
ShowLoopsOnError on
IgnoreBidirectionalLines off
ShowStorageClass off
ShowTestPointIcons on
ShowSignalResolutionIcons on
ShowViewerIcons on
SortedOrder off
ExecutionContextIcon off
ShowLinearizationAnnotations on
BlockNameDataTip off
BlockParametersDataTip off
BlockDescriptionStringDataTip off
ToolBar on
StatusBar on
BrowserShowLibraryLinks off
BrowserLookUnderMasks off
SimulationMode "normal"
LinearizationMsg "none"
Profile off
ParamWorkspaceSource "MATLABWorkspace"
AccelSystemTargetFile "accel.tlc"
AccelTemplateMakefile "accel_default_tmf"
AccelMakeCommand "make_rtw"
TryForcingSFcnDF off
RecordCoverage off
CovPath "/"
CovSaveName "covdata"
CovMetricSettings "dw"
CovNameIncrementing off
CovHtmlReporting on
CovForceBlockReductionOff on
covSaveCumulativeToWorkspaceVar on
CovSaveSingleToWorkspaceVar on
CovCumulativeVarName "covCumulativeData"
CovCumulativeReport off
CovReportOnPause on
CovModelRefEnable "Off"
CovExternalEMLEnable off
ExtModeBatchMode off
ExtModeEnableFloating on
ExtModeTrigType "manual"
ExtModeTrigMode "normal"
ExtModeTrigPort "1"
ExtModeTrigElement "any"
ExtModeTrigDuration 1000
ExtModeTrigDurationFloating "auto"
ExtModeTrigHoldOff 0
ExtModeTrigDelay 0
ExtModeTrigDirection "rising"
ExtModeTrigLevel 0
ExtModeArchiveMode "off"
ExtModeAutoIncOneShot off
ExtModeIncDirWhenArm off
ExtModeAddSuffixToVar off
ExtModeWriteAllDataToWs off
ExtModeArmWhenConnect on
ExtModeSkipDownloadWhenConnect off
ExtModeLogAll on
ExtModeAutoUpdateStatusClock on
BufferReuse on
ShowModelReferenceBlockVersion off
ShowModelReferenceBlockIO off
Array {
Type "Handle"
Dimension 1
Simulink.ConfigSet {
$ObjectID 1
Version "1.6.0"
Array {
Type "Handle"
Dimension 9
Simulink.SolverCC {
$ObjectID 2
Version "1.6.0"
StartTime "0.0"
StopTime "10.0"
AbsTol "auto"
FixedStep "auto"
InitialStep "auto"
MaxNumMinSteps "-1"
MaxOrder 5
ZcThreshold "auto"
ConsecutiveZCsStepRelTol "10*128*eps"
MaxConsecutiveZCs "1000"
ExtrapolationOrder 4
NumberNewtonIterations 1
MaxStep "auto"
MinStep "auto"
MaxConsecutiveMinStep "1"
RelTol "1e-3"
SolverMode "Auto"
Solver "ode45"
SolverName "ode45"
ShapePreserveControl "DisableAll"
ZeroCrossControl "UseLocalSettings"
ZeroCrossAlgorithm "Nonadaptive"
AlgebraicLoopSolver "TrustRegion"
SolverResetMethod "Fast"
PositivePriorityOrder off
AutoInsertRateTranBlk off
SampleTimeConstraint "Unconstrained"
InsertRTBMode "Whenever possible"
}
Simulink.DataIOCC {
$ObjectID 3
Version "1.6.0"
Decimation "1"
ExternalInput "[t, u]"
FinalStateName "xFinal"
InitialState "xInitial"
LimitDataPoints on
MaxDataPoints "1000"
LoadExternalInput off
LoadInitialState off
SaveFinalState off
SaveCompleteFinalSimState off
SaveFormat "Array"
SaveOutput on
SaveState off
SignalLogging on
InspectSignalLogs off
SaveTime on
ReturnWorkspaceOutputs off
StateSaveName "xout"
TimeSaveName "tout"
OutputSaveName "yout"
SignalLoggingName "logsout"
OutputOption "RefineOutputTimes"
OutputTimes "[]"
ReturnWorkspaceOutputsName "out"
Refine "1"
}
Simulink.OptimizationCC {
$ObjectID 4
Version "1.6.0"
Array {
Type "Cell"
Dimension 7
Cell "BooleansAsBitfields"
Cell "PassReuseOutputArgsAs"
Cell "PassReuseOutputArgsThreshold"
Cell "ZeroExternalMemoryAtStartup"
Cell "ZeroInternalMemoryAtStartup"
Cell "OptimizeModelRefInitCode"
Cell "NoFixptDivByZeroProtection"
PropName "DisabledProps"
}
BlockReduction on
BooleanDataType on
ConditionallyExecuteInputs on
InlineParams off
UseIntDivNetSlope off
InlineInvariantSignals off
OptimizeBlockIOStorage on
BufferReuse on
EnhancedBackFolding off
StrengthReduction off
EnforceIntegerDowncast on
ExpressionFolding on
BooleansAsBitfields off
EnableMemcpy on
MemcpyThreshold 64
PassReuseOutputArgsAs "Structure reference"
ExpressionDepthLimit 2147483647
FoldNonRolledExpr on
LocalBlockOutputs on
RollThreshold 5
SystemCodeInlineAuto off
StateBitsets off
DataBitsets off
UseTempVars off
ZeroExternalMemoryAtStartup on
ZeroInternalMemoryAtStartup on
InitFltsAndDblsToZero off
NoFixptDivByZeroProtection off
EfficientFloat2IntCast off
EfficientMapNaN2IntZero on
OptimizeModelRefInitCode off
LifeSpan "inf"
BufferReusableBoundary on
SimCompilerOptimization "Off"
AccelVerboseBuild off
}
Simulink.DebuggingCC {
$ObjectID 5
Version "1.6.0"
RTPrefix "error"
ConsistencyChecking "none"
ArrayBoundsChecking "none"
SignalInfNanChecking "none"
SignalRangeChecking "none"
ReadBeforeWriteMsg "UseLocalSettings"
WriteAfterWriteMsg "UseLocalSettings"
WriteAfterReadMsg "UseLocalSettings"
AlgebraicLoopMsg "warning"
ArtificialAlgebraicLoopMsg "warning"
SaveWithDisabledLinksMsg "warning"
SaveWithParameterizedLinksMsg "warning"
CheckSSInitialOutputMsg on
UnderspecifiedInitializationDetection "Classic"
MergeDetectMultiDrivingBlocksExec "none"
CheckExecutionContextPreStartOutputMsg off
CheckExecutionContextRuntimeOutputMsg off
SignalResolutionControl "UseLocalSettings"
BlockPriorityViolationMsg "warning"
MinStepSizeMsg "warning"
TimeAdjustmentMsg "none"
MaxConsecutiveZCsMsg "error"
SolverPrmCheckMsg "warning"
InheritedTsInSrcMsg "warning"
DiscreteInheritContinuousMsg "warning"
MultiTaskDSMMsg "error"
MultiTaskCondExecSysMsg "error"
MultiTaskRateTransMsg "error"
SingleTaskRateTransMsg "none"
TasksWithSamePriorityMsg "warning"
SigSpecEnsureSampleTimeMsg "warning"
CheckMatrixSingularityMsg "none"
IntegerOverflowMsg "warning"
Int32ToFloatConvMsg "warning"
ParameterDowncastMsg "error"
ParameterOverflowMsg "error"
ParameterUnderflowMsg "none"
ParameterPrecisionLossMsg "warning"
ParameterTunabilityLossMsg "warning"
FixptConstUnderflowMsg "none"
FixptConstOverflowMsg "none"
FixptConstPrecisionLossMsg "none"
UnderSpecifiedDataTypeMsg "none"
UnnecessaryDatatypeConvMsg "none"
VectorMatrixConversionMsg "none"
InvalidFcnCallConnMsg "error"
FcnCallInpInsideContextMsg "Use local settings"
SignalLabelMismatchMsg "none"
UnconnectedInputMsg "warning"
UnconnectedOutputMsg "warning"
UnconnectedLineMsg "warning"
SFcnCompatibilityMsg "none"
UniqueDataStoreMsg "none"
BusObjectLabelMismatch "warning"
RootOutportRequireBusObject "warning"
AssertControl "UseLocalSettings"
EnableOverflowDetection off
ModelReferenceIOMsg "none"
ModelReferenceVersionMismatchMessage "none"
ModelReferenceIOMismatchMessage "none"
ModelReferenceCSMismatchMessage "none"
UnknownTsInhSupMsg "warning"
ModelReferenceDataLoggingMessage "warning"
ModelReferenceSymbolNameMessage "warning"
ModelReferenceExtraNoncontSigs "error"
StateNameClashWarn "warning"
SimStateInterfaceChecksumMismatchMsg "warning"
StrictBusMsg "Warning"
LoggingUnavailableSignals "error"
BlockIODiagnostic "none"
}
Simulink.HardwareCC {
$ObjectID 6
Version "1.6.0"
ProdBitPerChar 8
ProdBitPerShort 16
ProdBitPerInt 32
ProdBitPerLong 32
ProdIntDivRoundTo "Undefined"
ProdEndianess "Unspecified"
ProdWordSize 32
ProdShiftRightIntArith on
ProdHWDeviceType "32-bit Generic"
TargetBitPerChar 8
TargetBitPerShort 16
TargetBitPerInt 32
TargetBitPerLong 32
TargetShiftRightIntArith on
TargetIntDivRoundTo "Undefined"
TargetEndianess "Unspecified"
TargetWordSize 32
TargetTypeEmulationWarnSuppressLevel 0
TargetPreprocMaxBitsSint 32
TargetPreprocMaxBitsUint 32
TargetHWDeviceType "Specified"
TargetUnknown off
ProdEqTarget on
}
Simulink.ModelReferenceCC {
$ObjectID 7
Version "1.6.0"
UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange"
CheckModelReferenceTargetMessage "error"
ModelReferenceNumInstancesAllowed "Multi"
ModelReferencePassRootInputsByReference on
ModelReferenceMinAlgLoopOccurrences off
}
Simulink.SFSimCC {
$ObjectID 8
Version "1.6.0"
SFSimEnableDebug on
SFSimOverflowDetection on
SFSimEcho on
SimBlas on
SimCtrlC on
SimExtrinsic on
SimIntegrity on
SimUseLocalCustomCode off
SimBuildMode "sf_incremental_build"
}
Simulink.RTWCC {
$BackupClass "Simulink.RTWCC"
$ObjectID 9
Version "1.6.0"
Array {
Type "Cell"
Dimension 6
Cell "IncludeHyperlinkInReport"
Cell "GenerateTraceInfo"
Cell "GenerateTraceReport"
Cell "GenerateTraceReportSl"
Cell "GenerateTraceReportSf"
Cell "GenerateTraceReportEml"
PropName "DisabledProps"
}
SystemTargetFile "grt.tlc"
GenCodeOnly off
MakeCommand "make_rtw"
GenerateMakefile on
TemplateMakefile "grt_default_tmf"
GenerateReport off
SaveLog off
RTWVerbose on
RetainRTWFile off
ProfileTLC off
TLCDebug off
TLCCoverage off
TLCAssert off
ProcessScriptMode "Default"
ConfigurationMode "Optimized"
ConfigAtBuild off
RTWUseLocalCustomCode off
RTWUseSimCustomCode off
IncludeHyperlinkInReport off
LaunchReport off
TargetLang "C"
IncludeBusHierarchyInRTWFileBlockHierarchyMap off
IncludeERTFirstTime off
GenerateTraceInfo off
GenerateTraceReport off
GenerateTraceReportSl off
GenerateTraceReportSf off
GenerateTraceReportEml off
GenerateCodeInfo off
RTWCompilerOptimization "Off"
CheckMdlBeforeBuild "Off"
Array {
Type "Handle"
Dimension 2
Simulink.CodeAppCC {
$ObjectID 10
Version "1.6.0"
Array {
Type "Cell"
Dimension 19
Cell "IgnoreCustomStorageClasses"
Cell "IgnoreTestpoints"
Cell "InsertBlockDesc"
Cell "SFDataObjDesc"
Cell "SimulinkDataObjDesc"
Cell "DefineNamingRule"
Cell "SignalNamingRule"
Cell "ParamNamingRule"
Cell "InlinedPrmAccess"
Cell "CustomSymbolStr"
Cell "CustomSymbolStrGlobalVar"
Cell "CustomSymbolStrType"
Cell "CustomSymbolStrField"
Cell "CustomSymbolStrFcn"
Cell "CustomSymbolStrFcnArg"
Cell "CustomSymbolStrBlkIO"
Cell "CustomSymbolStrTmpVar"
Cell "CustomSymbolStrMacro"
Cell "ReqsInCode"
PropName "DisabledProps"
}
ForceParamTrailComments off
GenerateComments on
IgnoreCustomStorageClasses on
IgnoreTestpoints off
IncHierarchyInIds off
MaxIdLength 31
PreserveName off
PreserveNameWithParent off
ShowEliminatedStatement off
IncAutoGenComments off
SimulinkDataObjDesc off
SFDataObjDesc off
IncDataTypeInIds off
MangleLength 1
CustomSymbolStrGlobalVar "$R$N$M"
CustomSymbolStrType "$N$R$M"
CustomSymbolStrField "$N$M"
CustomSymbolStrFcn "$R$N$M$F"
CustomSymbolStrFcnArg "rt$I$N$M"
CustomSymbolStrBlkIO "rtb_$N$M"
CustomSymbolStrTmpVar "$N$M"
CustomSymbolStrMacro "$R$N$M"
DefineNamingRule "None"
ParamNamingRule "None"
SignalNamingRule "None"
InsertBlockDesc off
SimulinkBlockComments on
EnableCustomComments off
InlinedPrmAccess "Literals"
ReqsInCode off
UseSimReservedNames off
}
Simulink.GRTTargetCC {
$BackupClass "Simulink.TargetCC"
$ObjectID 11
Version "1.6.0"
Array {
Type "Cell"
Dimension 17
Cell "GeneratePreprocessorConditionals"
Cell "IncludeMdlTerminateFcn"
Cell "CombineOutputUpdateFcns"
Cell "SuppressErrorStatus"
Cell "ERTCustomFileBanners"
Cell "GenerateSampleERTMain"
Cell "GenerateTestInterfaces"
Cell "ModelStepFunctionPrototypeControlCompliant"
Cell "CPPClassGenCompliant"
Cell "MultiInstanceERTCode"
Cell "PurelyIntegerCode"
Cell "SupportNonFinite"
Cell "SupportComplex"
Cell "SupportAbsoluteTime"
Cell "SupportContinuousTime"
Cell "SupportNonInlinedSFcns"
Cell "PortableWordSizes"
PropName "DisabledProps"
}
TargetFcnLib "ansi_tfl_table_tmw.mat"
TargetLibSuffix ""
TargetPreCompLibLocation ""
TargetFunctionLibrary "ANSI_C"
UtilityFuncGeneration "Auto"
ERTMultiwordTypeDef "System defined"
ERTMultiwordLength 256
MultiwordLength 2048
GenerateFullHeader on
GenerateSampleERTMain off
GenerateTestInterfaces off
IsPILTarget off
ModelReferenceCompliant on
ParMdlRefBuildCompliant on
CompOptLevelCompliant on
IncludeMdlTerminateFcn on
GeneratePreprocessorConditionals "Disable all"
CombineOutputUpdateFcns off
SuppressErrorStatus off
ERTFirstTimeCompliant off
IncludeFileDelimiter "Auto"
ERTCustomFileBanners off
SupportAbsoluteTime on
LogVarNameModifier "rt_"
MatFileLogging on
MultiInstanceERTCode off
SupportNonFinite on
SupportComplex on
PurelyIntegerCode off
SupportContinuousTime on
SupportNonInlinedSFcns on
SupportVariableSizeSignals off
EnableShiftOperators on
ParenthesesLevel "Nominal"
PortableWordSizes off
ModelStepFunctionPrototypeControlCompliant off
CPPClassGenCompliant off
AutosarCompliant off
UseMalloc off
ExtMode off
ExtModeStaticAlloc off
ExtModeTesting off
ExtModeStaticAllocSize 1000000
ExtModeTransport 0
ExtModeMexFile "ext_comm"
ExtModeIntrfLevel "Level1"
RTWCAPISignals off
RTWCAPIParams off
RTWCAPIStates off
GenerateASAP2 off
}
PropName "Components"
}
}
hdlcoderui.hdlcc {
$ObjectID 12
Version "1.6.0"
Description "HDL Coder custom configuration component"
Name "HDL Coder"
Array {
Type "Cell"
Dimension 1
Cell ""
PropName "HDLConfigFile"
}
HDLCActiveTab "0"
}
PropName "Components"
}
Name "Configuration"
CurrentDlgPage "Solver"
ConfigPrmDlgPosition " [ 280, 135, 1160, 765 ] "
}
PropName "ConfigurationSets"
}
Simulink.ConfigSet {
$PropName "ActiveConfigurationSet"
$ObjectID 1
}
BlockDefaults {
ForegroundColor "black"
BackgroundColor "white"
DropShadow off
NamePlacement "normal"
FontName "Helvetica"
FontSize 10
FontWeight "normal"
FontAngle "normal"
ShowName on
BlockRotation 0
BlockMirror off
}
AnnotationDefaults {
HorizontalAlignment "center"
VerticalAlignment "middle"
ForegroundColor "black"
BackgroundColor "white"
DropShadow off
FontName "Helvetica"
FontSize 10
FontWeight "normal"
FontAngle "normal"
UseDisplayTextAsClickCallback off
}
LineDefaults {
FontName "Helvetica"
FontSize 9
FontWeight "normal"
FontAngle "normal"
}
BlockParameterDefaults {
Block {
BlockType Demux
Outputs "4"
DisplayOption "none"
BusSelectionMode off
}
Block {
BlockType Inport
Port "1"
UseBusObject off
BusObject "BusObject"
BusOutputAsStruct off
PortDimensions "-1"
VarSizeSig "Inherit"
SampleTime "-1"
OutMin "[]"
OutMax "[]"
DataType "auto"
OutDataType "fixdt(1,16,0)"
OutScaling "[]"
OutDataTypeStr "Inherit: auto"
LockScale off
SignalType "auto"
SamplingMode "auto"
LatchByDelayingOutsideSignal off
LatchByCopyingInsideSignal off
Interpolate on
}
Block {
BlockType "S-Function"
FunctionName "system"
SFunctionModules "''"
PortCounts "[]"
SFunctionDeploymentMode off
}
Block {
BlockType SubSystem
ShowPortLabels "FromPortIcon"
Permissions "ReadWrite"
PermitHierarchicalResolution "All"
TreatAsAtomicUnit off
CheckFcnCallInpInsideContextMsg off
SystemSampleTime "-1"
RTWFcnNameOpts "Auto"
RTWFileNameOpts "Auto"
RTWMemSecFuncInitTerm "Inherit from model"
RTWMemSecFuncExecute "Inherit from model"
RTWMemSecDataConstants "Inherit from model"
RTWMemSecDataInternal "Inherit from model"
RTWMemSecDataParameters "Inherit from model"
SimViewingDevice off
DataTypeOverride "UseLocalSettings"
MinMaxOverflowLogging "UseLocalSettings"
}
Block {
BlockType Terminator
}
}
System {
Name "trajectory2"
Location [715, 251, 1295, 511]
Open on
ModelBrowserVisibility off
ModelBrowserWidth 200
ScreenColor "white"
PaperOrientation "landscape"
PaperPositionMode "auto"
PaperType "A4"
PaperUnits "centimeters"
TiledPaperMargins [1.270000, 1.270000, 1.270000, 1.270000]
TiledPageScale 1
ShowPageBoundaries off
ZoomFactor "100"
ReportName "simulink-default.rpt"
SIDHighWatermark 2
Block {
BlockType SubSystem
Name "Embedded\nMATLAB Function"
SID 1
Ports [1]
Position [305, 75, 375, 125]
LibraryVersion "1.30"
PermitHierarchicalResolution "ExplicitOnly"
MinAlgLoopOccurrences off
PropExecContextOutsideSubsystem off
RTWSystemCode "Auto"
FunctionWithSeparateData off
Opaque off
Array {
Type "Handle"
Dimension 0
PropName "AvailSigsLoadSave"
}
RequestExecContextInheritance off
MaskHideContents off
MaskType "Stateflow"
MaskDescription "Embedded MATLAB block"
MaskDisplay "disp('fcn');"
MaskSelfModifiable on
MaskIconFrame on
MaskIconOpaque off
MaskIconRotate "none"
MaskPortRotate "default"
MaskIconUnits "autoscale"
System {
Name "Embedded\nMATLAB Function"
Location [257, 457, 812, 717]
Open off
ModelBrowserVisibility off
ModelBrowserWidth 200
ScreenColor "white"
PaperOrientation "landscape"
PaperPositionMode "auto"
PaperType "A4"
PaperUnits "centimeters"
TiledPaperMargins [1.270000, 1.270000, 1.270000, 1.270000]
TiledPageScale 1
ShowPageBoundaries off
ZoomFactor "100"
SIDHighWatermark 11
SIDPrevWatermark 11
Block {
BlockType Inport
Name "data"
SID 1
Position [20, 101, 40, 119]
IconDisplay "Port number"
OutDataType "sfix(16)"
OutScaling "2^0"
}
Block {
BlockType Demux
Name " Demux "
SID 7
Ports [1, 1]
Position [270, 100, 320, 140]
Outputs "1"
}
Block {
BlockType "S-Function"
Name " SFunction "
SID 6
Tag "Stateflow S-Function trajectory2 2"
Ports [1, 1]
Position [180, 100, 230, 180]
FunctionName "sf_sfun"
PortCounts "[1 1]"
EnableBusSupport on
}
Block {
BlockType Terminator
Name " Terminator "
SID 9
Position [460, 111, 480, 129]
}
Line {
SrcBlock " SFunction "
SrcPort 1
DstBlock " Demux "
DstPort 1
}
Line {
SrcBlock "data"
SrcPort 1
DstBlock " SFunction "
DstPort 1
}
Line {
SrcBlock " Demux "
SrcPort 1
DstBlock " Terminator "
DstPort 1
}
}
}
Block {
BlockType Reference
Name "TCP/IP Receive"
SID 2
Ports [0, 1]
Position [55, 77, 165, 123]
LibraryVersion "1.84"
DialogController "instrumentcreatedialog"
DialogControllerArgs "DataTag0"
SourceBlock "instrumentlib/TCP//IP Receive"
SourceType "TCP/IP Receive"
Host "127.0.0.1"
Port "80"
DataSize "[1 3]"
EnableBlockingMode on
Timeout "10"
SampleTime "0.01"
DataType "double"
ByteOrder "BigEndian"
}
Line {
SrcBlock "TCP/IP Receive"
SrcPort 1
DstBlock "Embedded\nMATLAB Function"
DstPort 1
}
}
}
MatData {
NumRecords 1
DataRecord {
Tag DataTag0
Data " %)30 . : 8 ( 0 % \" $ ! 0 . . 8 ( ! "
" % \" $ ' 0 0 !P '1C<&EP<F( "
}
}
# Finite State Machines
#
# Stateflow Version 7.1 (R2009a) dated Jul 17 2009, 00:35:51
#
#
Stateflow {
machine {
id 1
name "trajectory2"
created "23-Feb-2010 11:53:03"
isLibrary 0
firstTarget 8
sfVersion 71014000.00001
}
chart {
id 2
name "Embedded\nMATLAB Function"
windowPosition [353.175 315 200.25 189.75]
viewLimits [0 156.75 0 153.75]
screen [1 1 1440 900 1.25]
treeNode [0 3 0 0]
firstTransition 5
firstJunction 4
viewObj 2
machine 1
toolbarMode LIBRARY_TOOLBAR
ssIdHighWaterMark 7
decomposition CLUSTER_CHART
type EML_CHART
firstData 6
chartFileNumber 2
disableImplicitCasting 1
eml {
name "fcn"
}
}
state {
id 3
labelString "eML_blk_kernel()"
position [18 64.5 118 66]
fontSize 12
chart 2
treeNode [2 0 0 0]
superState SUBCHART
subviewer 2
ssIdNumber 1
type FUNC_STATE
decomposition CLUSTER_STATE
eml {
isEML 1
script "function fcn(data)\n%#eml\neml.extrinsic('figure','scatter3','grid','hold','axis')\nfigure(1);\n%"
"hold on\n\nscatter3(data(1),data(2),data(3))\n%scatter3(data,10,10)\n%axis on\ngrid"
editorLayout "100 M4x1[205 142 1080 733]"
}
}
junction {
id 4
position [23.5747 49.5747 7]
chart 2
linkNode [2 0 0]
subviewer 2
ssIdNumber 3
type CONNECTIVE_JUNCTION
}
transition {
id 5
labelString "{eML_blk_kernel();}"
labelPosition [32.125 19.875 102.544 14.964]
fontSize 12
src {
intersection [0 0 1 0 23.5747 14.625 0 0]
}
dst {
id 4
intersection [7 0 -1 -1 23.5747 42.5747 0 0]
}
midPoint [23.5747 24.9468]
chart 2
linkNode [2 0 0]
dataLimits [23.575 23.575 14.625 34.575]
subviewer 2
drawStyle SMART
executionOrder 1
ssIdNumber 2
}
data {
id 6
ssIdNumber 4
name "data"
linkNode [2 0 0]
scope INPUT_DATA
machine 1
props {
array {
size "-1"
}
type {
method SF_INHERITED_TYPE
primitive SF_DOUBLE_TYPE
}
complexity SF_COMPLEX_INHERITED
}
dataType "Inherit: Same as Simulink"
}
instance {
id 7
name "Embedded\nMATLAB Function"
machine 1
chart 2
}
target {
id 8
name "sfun"
description "Default Simulink S-Function Target."
machine 1
linkNode [1 0 0]
}
}
I can't see creating socket and binding to it in your C code. Are you sure that you're binding on 127.0.0.1 and port 80? Are you sure that there's no some apache running on the server on port 80?
http://www.linuxhowtos.org/C_C++/socket.htm
Also:
sock_err = send(csock, T, 3*sizeof(double), 0);
I don't also see T in your code, which is probably not the issue, but it doesn't seem to be the datasend pointer to mxArray.