How to display matlab content into columns using fprintf - matlab

I'm looking to display data in two columns. The first column will have a movies name and the second a rating out of 5. I want the data to be displayed in such a way that the ratings, regardless of the length of the movie title all display in on vertical line. I currently have:
Toy Story (1995) : 4
GoldenEye (1995) : 3
Seven (Se7en) (1995) : 4
Braveheart (1995) : 1
Bad Boys (1995) : 3
Batman Forever (1995) : 2
Star Wars (1977) : 5
Shawshank Redemption, The (1994) : 5
Ace Ventura: Pet Detective (1994) : 3
Aladdin (1992) : 3
I'm using the following code:
fprintf('%s : \t %d\n', movieList{i},user_ratings(i));
where the above line is obviously in a loop. I tried using a tab to see if things would line up but clearly not much luck. Any ideas on how I could achieve this?

If you would like to keep things simple and your loop, you may try this -
lens = cellfun(#numel,movieList);
pdlens = max(lens) - lens;
for k = 1:numel(movieList)
fprintf('%s%s :\t%d\n', movieList{k},repmat(' ',1,pdlens(k)),user_ratings(k))
end
Output -
Toy Story (1995) : 4
GoldenEye (1995) : 3
Seven (Se7en) (1995) : 4
Braveheart (1995) : 1
Bad Boys (1995) : 3
Batman Forever (1995) : 2
Star Wars (1977) : 5
Shawshank Redemption, The (1994) : 5
Ace Ventura: Pet Detective (1994) : 3
Aladdin (1992) : 3
Alternate solution based on arrayfun -
spc = repmat(' ',numel(movieList),1)
pdc = arrayfun(#(x,t) repmat(x,1,t),spc,pdlens,'uni',0) %//pdlens is from earlier code
spcell = repmat(cellstr({' '}),numel(movieList),1)
out = strcat(movieList,pdc,':',spcell,num2str(user_ratings')) %//'
char(out) %// Display the text

You can try this, it really not beautifull but :
maxVal = 0
[~,nbMovie] = size(movieList);
for i = 1:nbMovie
maxVal = max(maxVal,length(movieList{i}))
end
wordPrint = strcat('%',int2str(maxVal),'s');
totalPrint = strcat(wordPrint,' : %f\n');
for i = 1:nbMovie
fprintf(totalPrint ,movieList{i},user_ratings(i));
end
EDIT
And for a left align for the word use the symbol '-' before the number, like this :
wordPrint = strcat('%-',int2str(maxVal),'s');

Related

How do I tell my graph coloring problem program to only assign color 1 one time?

Basically, I have a graph coloring program where each node with an edge to another node has to be different colors. Here, is my code:
node(1..4).
edge(1,2).
edge(2,3).
edge(3,4).
edge(4,1).
edge(2,4).
color(1..3).
{ assign(N,C) : color(C) } = 1 :- node(N).
1 { assign(N,1) : color(1) } 1 :- node(N). %line in question
:- edge(N,M), assign(N,C), assign(M,C).
How would I tell the program to only assign color 1, once? The line labeled %line in question is the line giving me problems. Here is another solution I tried that didn't work:
node(1..4).
edge(1,2).
edge(2,3).
edge(3,4).
edge(4,1).
edge(2,4).
color(1..3).
{ assign(N,C) : color(C) } = 1 :- node(N).
:- edge(N,M), assign(N,C), assign(M,C).
vtx(Node, Color) :- node(Node), color(Color).
1 { vtx(N, 1) : color(1) } 1 :- node(N).
#show vtx/2.
If anyone could help me out it would be much appreciated.
In this simple case of restricting a single color to be used once, you can write the a single constraint
:- assign(N, 1), assign(M, 1), node(N), node(M), N!=M.
Actually, the line you marked as in question :
1 { assign(N,1) : color(1) } 1 :- node(N). %line in question
can be translated as
If N is a node, we will (and we must) assign color(1) to node(N) and only assign once, i.e. If node(i) is true, we will have exactly one node(i, 1).
Therefore, with this rule and your facts node(1..4), you will immediately get assign(1,1), assign(2,1), assign(3,1), assign(4,1). This is defninitely unsatisfiable under color problem (with the last constraint).
Back to your requirement:
How would I tell the program to only assign color 1, once?
The problem here is the constraint you set in the line: "color 1 is assigned only once" applies to each node(i), i=1,2,3,4 instead of all nodes.
To make it clearer, you might as well consider that this line would be instantiated as:
1 { assign(1,1) : color(1) } 1 :- node(1).
1 { assign(2,1) : color(1) } 1 :- node(2).
1 { assign(3,1) : color(1) } 1 :- node(3).
1 { assign(4,1) : color(1) } 1 :- node(4).
With node(1..4) all true, we will have assign(1,1), assign(2,1), assign(3,1), assign(4,1).
What you want is assign(N, 1) appears once and only once in the answer, thus in your rule, this should be true with no premiere condition.
Therefore, change the problem line into:
{ assign(N,1): node(N), color(1) } = 1. %problem line changed
You will get the proper assignment:
clingo version 5.4.0
Reading from test.lp
Solving...
Answer: 1
assign(2,2) assign(1,3) assign(3,3) assign(4,1)
Answer: 2
assign(1,2) assign(2,3) assign(3,2) assign(4,1)
Answer: 3
assign(2,1) assign(1,3) assign(3,3) assign(4,2)
Answer: 4
assign(2,1) assign(1,2) assign(3,2) assign(4,3)
SATISFIABLE
Intuitively, this line means the assign(N, 1) should be in answer set under no condition, as long as N is a node. This will count all nodes instead of every single one.

stockage in structure and iteration

I would like to understand one thing :
When I write : Propreties.Device.Time = Data.Device(lobo(:,2),1) - Data.Device(lobo(:,1),1) I obtain a stockage of all the differencies (it's great)
But when I write : Propreties.Device.Prop = sum(Data.Device(lobo(:,1) : lobo(:,2)),2)*dt I don't obtain a stockage of all results (that I would like to obtain as previous exemple) but an overwrite of each of them so at the end I have only one value :-/
Could someone explain to me what differs between the two examples and what I could implement to obtain in the second example the same type of result as in the first (ie a list of results and not a single result) (without making a loop) ?
(Matlab verison : R2017a)
Some data for exemple :
Data.Device = [1.86000000000000 675 0;1.87000000000000 685 0;1.88000000000000 695 0;1.89000000000000 705 0;1.90000000000000 710 5;1.91000000000000 715 50;1.92000000000000 700 120;1.93000000000000 685 180;1.94000000000000 655 235;1.95000000000000 620 285;1.96000000000000 565 305;1.97000000000000 505 315;1.98000000000000 435 335;1.99000000000000 360 345;2 285 355];
lobo = [1 5; 6 15];
dt = 0.01
Propreties.Device.Time = Data.Device(lobo(:,2),1) - Data.Device(lobo(:,1),1);
Propreties.Device.Prop = sum(Data.Device(lobo(:,1) : lobo(:,2)),2)*dt

An issue with argument "sortv" of function seqIplot()

I'm trying to plot individual sequences by means of function seqIplot() in TraMineR. These individual sequences represent work trajectories, completed by former school's graduates via a WEB questionnaire.
Using argument "sortv", I'd like to sort my sequences according to the order of the levels of one covariate, the year of graduation, named "PROMO".
"PROMO" is a factor variable contained in a data frame named "covariates.seq", gathering covariates together:
str(covariates.seq)
'data.frame': 733 obs. of 6 variables:
$ ID_SQ : Factor w/ 733 levels "1","2","3","5",..: 1 2 3 4 5 6
7 8 9 10 ...
$ SEXE : Factor w/ 2 levels "Féminin","Masculin": 1 1 1 1 2 1
1 2 2 1 ...
$ PROMO : Factor w/ 6 levels "1997","1998",..: 1 2 2 4 4 3 2 2
2 2 ...
$ DEPARTEMENT : Factor w/ 10 levels "BC","GCU","GE",..: 1 4 7 8 7 9
9 7 7 4 ...
$ NIVEAU_ADMISSION: Factor w/ 2 levels "En Premier Cycle",..: NA 1 1 1 1
1 NA 1 1 1 ...
$ FILIERE_SECTION : Factor w/ 4 levels "Cursus Classique",..: NA 4 2 NA
1 1 NA NA 4 3 ..
I'm also using "SEXE", the graduates' gender, as a grouping variable. To plot the individual sequences so, my command is as follows:
seqIplot(sequences, group = covariates.seq$SEXE,
sortv = covariates.seq$PROMO,
cex.axis = 0.7, cex.legend = 0.7)
I expected that, by using a process time axis (with the year of graduation as sequence-dependent origin), sorting the sequences according to the order of the levels of "PROMO" would give a plot with groups of sequences from the longest (for the older graduates) to the shortest (for the younger graduates).
But I've got an issue: in the output plot, the sequences don't appear to be correctly sorted according to the levels of "PROMO". Indeed, by using "sortv = covariates.seq$PROMO" as in the command above, the plot doesn't show groups of sequences from the longest to the shortest, as expected. It looks like the plot obtained without using the argument "sortv" (see Figures below).
Without using argument "sortv"
Using "sortv = covariates.seq$PROMO"
Note that I have 733 individual sequences in my object "sequences", created as follows:
labs <- c("En poste","Au chômage (d'au moins 6 mois)", "Autre situation
(d'au moins 6 mois)","En poursuite d'études (thèse ou hors
thèse)", "En reprise d'études / formation (d'au moins 6 mois)")
codes <- c("En poste", "Au chômage", "Autre situation", "En poursuite
d'études", "En reprise d'études / formation")
sequences <- seqdef(situations, alphabet = labs, states = codes, left =
NA, right = "DEL", missing = NA,
cnames = as.character(seq(0,7400/365,1/365)),
xtstep = 365)
The values of the covariates are sorted in the same order as the individual sequences. The covariate "PROMO" doesn't contain any missing value.
Something's going wrong, but what?
Thank you in advance for your help,
Best,
Arnaud.
Using a factor as sortv argument in seqIplot works fine as illustrated by the example below:
sdc <- c("aabbccdd","bbbccc","aaaddd","abcabcab")
sd <- seqdecomp(sdc, sep="")
seq <- seqdef(sd)
fac <- factor(c("2000","2001","2001","2000"))
par(mfrow=c(1,3))
seqIplot(seq, with.legend=FALSE)
seqIplot(seq, sortv=fac, with.legend=FALSE)
seqlegend(seq)

Handling hash tables in custom objects

Our monitoring system has a REST API that I am trying to retrieve properties from, then output them to a custom object. A couple of the property values are hash tables.
In addition to keeping the custom objects for use in Powershell, I would like to export them to CSV, so I need those hash tables to be something else, so I don't end up with Syste.Object[] in those columns.
The object returned from the API looks like this (truncated):
$allServices[0]
alertStatus : none
ignoreSSL : True
description : Test service
stopMonitoring : False
stopMonitoringByFolder : False
useDefaultLocationSetting : False
serviceProperties : {}
transition : 1
alertStatusPriority : 100000
serviceFolderId : 1
script :
disableAlerting : False
individualAlertLevel : warn
checkpoints : {#{id=1; geoInfo=Overall; smgId=0}, #{id=2; geoInfo=US - Los Angeles; smgId=1}, #{id=3; geoInfo=US - Washington DC; smgId=2}, #{id=4; geoInfo=US - San Francisco; smgId=3}...}
pageLoadAlertTimeInMS : 30000
sdtStatus : none-none-none
serviceStatus : alive
method : tabledriven
id : 1
Then checkpoints looks like this:
$allServices[0].checkpoints
id geoInfo smgId
-- ------- -----
1 Overall 0
2 US - Los Angeles 1
3 US - Washington DC 2
4 US - San Francisco 3
5 Europe - Dublin 4
6 Asia - Singapore 5
What is the best way to deal with the checkpoints property?
Thanks.
Convert checkpoints (and possibly serviceProperties) to a JSON string.
$allServicesCSV = foreach ($srv in $allServices) {
$srv = $srv.PSObject.Copy() # shallow copy
$srv.checkpoints = ConvertTo-Json $srv.checkpoints -Compress
$srv
}
Well, the requirements changed, so I only need to output to json/XML and not to CSV, making this much easier. Thanks.

POS tagging in Scala

I tried to POS tag a sentence in Scala using Stanford parser like below
val lp:LexicalizedParser = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz");
lp.setOptionFlags("-maxLength", "50", "-retainTmpSubcategories")
val s = "I love to play"
val parse :Tree = lp.apply(s)
val taggedWords = parse.taggedYield()
println(taggedWords)
I got an error type mismatch; found : java.lang.String required: java.util.List[_ <: edu.stanford.nlp.ling.HasWord] in the line val parse :Tree = lp.apply(s)
I don't know whether this is the right way of doing it or not. Are there any other easy ways of POS tagging a sentence in Scala?
You might like to consider the FACTORIE toolkit (http://github.com/factorie/factorie). It is a general library for machine learning and graphical models that happens to include an extensive suite of natural language processing components (tokenization, token normalization, morphological analysis, sentence segmentation, part-of-speech tagging, named entity recognition, dependency parsing, mention finding, coreference).
Furthermore it is written entirely in Scala, and it is released under the Apache License.
Documentation is currently sparse, but will be improving in the coming months.
For example, once Maven-based installation is finished you can type at the command line:
bin/fac nlp --pos1 --parser1 --ner1
to launch a socket-listening multi-threaded NLP server. Then query it by piping plain text to its socket number:
echo "Mr. Jones took a job at Google in New York. He and his Australian wife moved from New South Wales on 4/1/12." | nc localhost 3228
The output is then
1 1 Mr. NNP 2 nn O
2 2 Jones NNP 3 nsubj U-PER
3 3 took VBD 0 root O
4 4 a DT 5 det O
5 5 job NN 3 dobj O
6 6 at IN 3 prep O
7 7 Google NNP 6 pobj U-ORG
8 8 in IN 7 prep O
9 9 New NNP 10 nn B-LOC
10 10 York NNP 8 pobj L-LOC
11 11 . . 3 punct O
12 1 He PRP 6 nsubj O
13 2 and CC 1 cc O
14 3 his PRP$ 5 poss O
15 4 Australian JJ 5 amod U-MISC
16 5 wife NN 6 nsubj O
17 6 moved VBD 0 root O
18 7 from IN 6 prep O
19 8 New NNP 9 nn B-LOC
20 9 South NNP 10 nn I-LOC
21 10 Wales NNP 7 pobj L-LOC
22 11 on IN 6 prep O
23 12 4/1/12 NNP 11 pobj O
24 13 . . 6 punct O
Of course there is a programmatic API to all this functionality as well.
import cc.factorie._
import cc.factorie.app.nlp._
val doc = new Document("Education is the most powerful weapon which you can use to change the world.")
DocumentAnnotatorPipeline(pos.POS1).process(doc)
for (token <- doc.tokens)
println("%-10s %-5s".format(token.string, token.posLabel.categoryValue))
will output:
Education NN
is VBZ
the DT
most RBS
powerful JJ
weapon NN
which WDT
you PRP
can MD
use VB
to TO
change VB
the DT
world NN
. .
I found a very simple way to do POS tagging in Scala
Step 1
Download stanford tagger version 3.2.0 form the link below
http://nlp.stanford.edu/software/stanford-postagger-2013-06-20.zip
Step 2
Add stanford-postagger jar present in the folder to your project and also place the english-left3words-distsim.tagger file present in the models folder in your project
Then, with the code below you can pos tag a sentence in Scala
val tagger = new MaxentTagger(
"english-left3words-distsim.tagger")
val art_con = "My name is Rahul"
val tagged = tagger.tagString(art_con)
println(tagged)
Output: My_PRP$ name_NN is_VBZ Rahul_NNP
I believe the API of the Stanford Parser has changed somewhat, as it does sometimes. apply has the signature, public Tree apply(java.util.List<? extends HasWord> words), and this is what you see in the error message.
What you should use now is parse, which has the signature public Tree parse(java.lang.String sentence).