How to create a 3D faceted model in MATLAB
What would be the best way to create a 3D MATLAB model made of (triangular) facets, similar to this one?
I would also like to be able to define normal and surface vectors for each facet if possible.
Any help is appreciated.
See also questions close to this topic

Latex listings package cannot include matlab code with percentage symbol
I'm writing a Matlab project report using latex. I use
lstinputlisting
command inlistings
package to parse a Matlab code file.The original Matlab code has following lines.
s = functions(solvers{idx}); fname = s.function; fprintf("%s : \n", fname);
The percentage symbol in the code file trigger compile error.
! LaTeX Error: Environment CJK* undefined. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. ... l.19 fprintf("% s : \n", fname);
When I change the language from Matlab into C, the error disappear. I guess there are some bugs inside the Matlab syntax file inside listings package.
Is there any way to fix this problem?
My listings configuration is
\lstset{% language = Matlab, tabsize=4, frame=shadowbox, %把代码用带有阴影的框圈起来 commentstyle=\color{red!50!green!50!blue!50},%浅灰色的注释 rulesepcolor=\color{red!20!green!20!blue!20},%代码块边框为淡青色 keywordstyle=\color{blue!90}\bfseries, %代码关键字的颜色为蓝色，粗体 showstringspaces=false,%不显示代码字符串中间的空格标记 stringstyle=\ttfamily, % 代码字符串的特殊格式 keepspaces=true, % breakindent=22pt, % numbers=left,%左侧显示行号 往左靠,还可以为right，或none，即不加行号 stepnumber=1,%若设置为2，则显示行号为1,3,5，即stepnumber为公差,默认stepnumber=1 %numberstyle=\tiny, %行号字体用小号 numberstyle={\color[RGB]{0,192,192}\tiny} ,%设置行号的大小，大小有tiny,scriptsize,footnotesize,small,normalsize,large等 numbersep=8pt, %设置行号与代码的距离，默认是5pt basicstyle=\footnotesize, % 这句设置代码的大小 showspaces=false, % flexiblecolumns=true, % breaklines=true, %对过长的代码自动换行 breakautoindent=true,% breakindent=4em, % escapebegin=\begin{CJK*}{GBK}{hei},escapeend=\end{CJK*}, aboveskip=1em, %代码块边框 tabsize=2, showstringspaces=false, %不显示字符串中的空格 backgroundcolor=\color[RGB]{245,245,244}, %代码背景色 %backgroundcolor=\color[rgb]{0.91,0.91,0.91} %添加背景色 escapeinside=``, %在``里显示中文 %% added by http://bbs.ctex.org/viewthread.php?tid=53451 fontadjust, captionpos=t, framextopmargin=2pt,framexbottommargin=2pt,abovecaptionskip=3pt,belowcaptionskip=3pt, xleftmargin=4em,xrightmargin=4em, % 设定listing左右的空白 texcl=true, % 设定中文冲突，断行，列模式，数学环境输入，listing数字的样式 extendedchars=false,columns=flexible,mathescape=true % numbersep=1em }
And I use
\lstinputlisting{./code/main.m}
to include file. 
Distance Calculations for Nearest Mean Classifer
Greetins,
How can I calculate how many distance calculations would need to be performed to classify the IRIS dataset using Nearest Mean Classifier.
I know that IRIS dataset has 4 features and every record is classified according to 3 different labels.
According to some textbooks, the calculation can be carried out as follow:
However, I am lost on these different notations and what does this equation mean. For example, what is s^2 is in the equation?

matlab: addition of symbolic matrices along an unused dimension
How can symbolic matrices collected in a cell array be summed along an unused dimension? Assume, for reasons beyond the scope of this post, that the matrices must be the elements of a cell array, rather than planes of a higherdimensional matrix. What follows is a brief demonstration of the problem.
Suppose we have a cell array of 2D
sym
vectors prepared as follows:a = vpa(ones(2,2)); c = {a; 2*a; 3*a};
Despite the fact that it is possible to make multidimensional symbolic matrices with newer versions of matlab (e.g.,
sym('c', [2 2 2])
), addition of 2Dsym
matrices along a third dimension failssum(cat(3, c{:}), 3) Error using symengine Arguments must be 2dimensional.
With numeric inputs, the operation is successful:
a = ones(2,2); c = {a; 2*a; 3*a}; sum(cat(3,c{:}), 3) 6 6 6 6
Edit:
In fact, the problem of multidimensional addition is more general than I had thought:
sum
cannot be applied to anysym
matrix of dimensionality greater than 2.a=vpa(ones(2,2)); sum(a,1) [ 2.0, 2.0] sum(a,2) 2.0 2.0 a = vpa(ones(2,2,2)); sum(a,1) % fails sum(a,2) % fails sum(a,3) % fails
Manual addition of planes along a third dimension works, so iterative addition is an option, though
sum
would be preferable:a=vpa(ones(2,2,2)); plus(a(:,:,1), a(:,:,2)) [ 2.0, 2.0] [ 2.0, 2.0]
Edit #2:
According to this page, the problem is apparently unavoidable since support for dimensionality >2 is explicitly not offered.
Unlike the MATLAB® sum, the symbolic sum function does not work on multidimensional arrays. For details, follow the MATLAB sum page.
Nevertheless, suggestions on alternatives are still welcome.

How do I enter an array in D3.js?
Does It have a way to enter an entire array from my data set in D3.js? Or do I have to clean up It before enter?
An example of my dataset .jason is here:
[ { "promoter": "Vigun01", "upstream": "[2, 57, 150, 376]" }, { "promoter": "Vigun01", "upstream": "[500, 732, 765]" }, { "promoter": "Vigun01", "upstream": "[675]" }, { "promoter": "Vigun02", "upstream": "[623]" }, { "promoter": "Vigun03", "upstream": "[133, 601]" }, { "promoter": "Vigun04", "upstream": "[599, 650]" }, { "promoter": "Vigun05", "upstream": "[50, 789]" } ]
and my script in D3.js is here:
var svg = d3.select("#chartarea") .append("svg") .attr("width", "400") .attr("height", "400"); d3.json("data/dataset.json").then(function(data){ data.forEach(d => { d.upstream = +d.upstream; }); console.log(data); var y = d3.scaleBand() .domain(data.map(function(d){ return d.promoter; })) .range([0, 400]) .paddingInner(0.2) .paddingOuter(0.2); var x = d3.scaleLinear() .domain([0,1000]) .range([0,400]); var line = svg.selectAll("line") .data(data); line.enter() .append('line') .attr('x1', 0) .attr('y1', (d,i)=>y(d.promoter)) .attr('x2', 400) .attr('y2', (d,i)=>y(d.promoter)) .attr('strokewidth', 1) .attr('stroke', 'black'); var circle = svg.selectAll("circle") .data(data) .enter() .append("circle") .attr("cy", function(d){ return y(d.promoter) }) .attr("cx", function(d){ return x(d.upstream) }) .attr("r", 5) .attr("fill", function(d) { return "black"; }); }).catch(function(error){ console.log(error) });
I can draw single inputs, like ("Vigun01", "10"), but I can't if I have a entire array.
It's ok for me if convert ("Vigun01", "[1,2,3,4]") to many inputs like ("Vigun01", "1"), ("Vigun01", "2"), ("Vigun01", "3"), ("Vigun01", "4") but how do I do it inside my dataset?

semantic graph based on Wikipedia
I have three problems in one.
1) first of all, I try to extract the tree structure from the portals of Wikipedia. For example, the Genetics portal derives from the Molecular and cellular biology portal, which derives from the Biological science portal, which finally derives from the Natural and physical sciences portal.
https://en.wikipedia.org/wiki/Portal:Contents/Portals#Culture_and_the_arts
2) Then I try to modify this tree structure. Indeed, it is rather a nonoriented graph with cycles that has the shape of a tree. Let me explain. It may turn out that the same portal derives from two different portals and you have to join the two pieces. If a gate B derives from a gate A1 and also from a gate A2 then the two points B are "superimposed".
3) Finally, I try to graphically represent this very large graph in Python.
Thank you in advance for your help, Have a good evening

How can I get the points between two points on a line?
How can I get the points between a start point
(x1, y1)
and end point(x2, y2)
on a line. I need these points to check if it's located in free space or on an obstacle. How can I do this in Java?public void paint(Graphics g) { super.paint(g); g.drawLine(50, 50, 400, 400); }
Is there an existing function that can help me get these points?

WebView doesn't rotate WebGL 3dEarth website stored in assets
I want to display a 3d earth through the WebView with WebGL. I took the 3d earth from: http://www.webglearth.org/
I've got the API.js and a .html file. I moved them to the Android assets folder and try to start the app. The webview displays the earth, but if I try to rotate it, the earth is hang at some point.
But the webview still responds to inputs, like if I click a marker on the map. Only the movement doesn't work and I don't know why. JavaScript for WebView is activated.

Bar color definition in matplotlib 3D bar
I wish to visualize a 3D bar plot in which the bars below a specified level
base
all have a specified color (in my case, no color at all (0,0,0,0)
). There are a few posts regarding this topic such as here and here also but I was not able to obtain the expected results.The idea is to prescribe the
color
feature of the bars as an array. This array is modified previously to set the color of the bars below the desired level. In the case below, the level is2
, i.e., bars with height below 2 should have no color and not appear on the plot. However, even though thecolor
array seems correct, some of bars still show up. I tried a couple of different approaches, but unsuccessful and I am not able to understand why.I appreciate the attention. I am using Spyder with Python 3.7.1 on Windows 7. Code below (notice every time the code is run, different data will be generated due to the use of np.random)
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm fig = plt.figure(figsize=(9, 4)) ax1 = fig.add_subplot(121, projection='3d') ax2 = fig.add_subplot(122, projection='3d') # Random data x = np.tile([np.linspace(0,0.2,4+1, endpoint=True)],len(np.linspace(0,0.2,4+1, endpoint=True))).flatten() y = np.repeat([np.linspace(0,0.2,4+1, endpoint=True)],len(np.linspace(0,0.2,4+1, endpoint=True))) dx = x[1]x[0] dy = dx base = 2 bottom = np.ones(len(x))*base top = np.random.uniform(3, 3, (len(x),1)).flatten() cmap = cm.get_cmap('rainbow') # Colormap to be used as basis rgba = [cmap((inp.min(top))/(np.max(top)np.min(top))) for i in top] # scale each heights and get rgba ax1.bar3d(x, y, bottom, dx, dy, top, color = rgba) ax1.set_zlim(1.5*np.min(top), 1.5*np.max(top)) ax1.set_title('No modification on colors below 2') # Attempt 1 get = [index for (index, value) in enumerate(top) if value <= base] for g in get: rgba[g] = (0,0,0,0) ## Attempt 2 #rgba_del = [cmap((knp.min(top))/(np.max(top)np.min(top))) for k in top if k<base] #for el in rgba_del: # if el in rgba: # rgba[rgba.index(el)] = (0,0,0,0) ax2.bar3d(x, y, bottom, dx, dy, top, color = rgba) ax2.set_zlim(1.5*np.min(top), 1.5*np.max(top)) ax2.set_title('Some bars below 2 still showing! Why?') ## Attempt 2 #for b in range(len(top)): # ax2.bar3d(x[b], y[b], bottom[b], dx, dy, top[b], color = rgba[b]) #ax2.set_zlim(1.5*np.min(top), 1.5*np.max(top))

iOS 3DAnimations: Issues when rotating multiple superposed views
Issue
When flipping (e.g. pi rotation) views at the same time on the same axis, the view hierarchy (which one is in front and which one is behind) seems to be disturbed.
Detailed explanations
In the GIF below, the grey view with the swift icon is in front and the blue view is behind.
You can notice that when the first rotation of the grey view reaches pi / 2, its transparency seems to be altered. In addition, when the grey finishes its first rotation, instead of staying behind the blue view, it appears to be in front during all the next rotation.
Now repeating the exact same animation, the blue view has now no colours applied but it is still in the view hierarchy behind the grey view, and still animated.
Desired Result
I am trying to achieved the same animation keeping the blue view on top of the grey view, without having any apparent transparency change on the grey view. I use
UIViewPropertyAnimator
to be able to scrub the animation later on.The Code
The following code describes a simplified flip method (as an UIView extension) the animation is based on.
extension UIView{ func flipping(_ times: Int = 1, to direction: FoldingDirection, within duration: Double = 0.01, startAfter delay: Double = 0) { guard times > 0 else { return } // resets the layer anchor point depending on the current transform states of the view (calling a specific method) self.setAnchorPoint(at: direction.anchor()) // adding perspective effect self.layer.transform.m34 = 1 / 250 // setting rotation axis let axis: CGPoint = { switch direction { case .right, .left: return CGPoint(x: 1, y: 0) default: return CGPoint(x: 0, y: 1) } }() let flipDuration = duration > 0 ? duration / Double(times) : 0.01 // creating animator let animator = UIViewPropertyAnimator(duration: flipDuration, curve: .linear) { self.layer.transform = CATransform3DRotate(self.layer.transform, .pi, axis.y, axis.x, 0) } animator.startAnimation(afterDelay: delay) animator.addCompletion { (position) in if position == .end { self.flipping(times  1, to: direction, within: duration * ( 1  1 / Double(times)), startAfter: 0) } } } }
Calling the animation:
greyView.flipping(3, to: .right, within: 9, startAfter: 0) blueView.flipping(2, to: .right, within: 6, startAfter: 3)
Thanks for your help!
EDIT After running multiple tests, it seems the view hierarchy is indeed changed during the animation: the rotation seems to be occurring behind the view plane.

Drupal 8: how to link a facet to a custom facet processor module
I've found some guidance on creating a custom facet module in Drupal 8; however, they skip instructions on how to link the facet to the custom processor.
http://tech.dichtlog.nl/facets/2015/11/30/facetsprocessor.html
Just writes, "Apply the processor to the facet"
Elsewhere, I've found references to this linking being done in Configuration => Facets => Edit a facet => Advanced Settings. However, I don't see any option to use a custom facet here, even after I installed the above example facet module to test this.
Thanks for any help.

ggplot  use pie chart to visualize number of items in each group in terms of percentages  R
I want to create two pie chart to show number of people in each level of the factor variable. However, I want to obtain two pie charts, one for two groups.
Here is an example:
library(ggplot2) library(dplyr) df < filter(diamonds, color %in% c("E", "D")) ggplot(df,aes(x= "", fill=cut)) + geom_bar()+ facet_wrap(~color)+ ggtitle(" ") + coord_polar("y", start=0)
How can I Express the count of items per each group (cut) per each facet (color) as percentage? So on the end I would obtain two full pie charts with the precentages written inside the pie chart.

Force geom_bar minimum to minimum barheight in facet grid
with the following data:
dat < data.frame(A = c(1,1,1,1,2,2,2,2), B = c(1,1,2,2,1,1,2,2), C = c(1,2,1,2,1,2,1,2), data = c(4, 7, 6, 8, 4, 6, 7, 10))
I would like to make a facet grid, as below:
ggplot(dat, aes(x=C, y=data, group=C, fill=C)) + geom_bar(stat="identity", alpha=0.3) + facet_grid(B ~ A)
However, I would like for the minimum of the barheight to be dependent on the particular facet; particularly, across the row. I know if I had not used a facet, this could have been done in the aesthetic by taking
y = data  min(data)
, but I am not sure how to represent this while maintaining the faceting. I am almost sure thatggplot2
has a super intuitive/easy solution for this, but I can't find it after a while googling around.Any help appreciated!

How to simplify shapes for triangulation with three.js and jsclipper
I try to display geometry which is constructed by constructpath commands like moveto lineto beziercurveto in Three.js. Therefore I create a THREE.ShapePath(); and execute the command toShapes(isClockwise). After this I use THREE.ExtrudeBufferGeometry to create the 3D shape.
Unfortunately the shapes are sometimes really complex and are not created correctly which means they are distorted.
Using libtess as triangulation library solves some issues. But I have still distorted geometry.
Now I want to use jsclipper to simplify the shapes prior triangulation.
I modified three.js in such way:
in the method addShape in ExtrudeBufferGeometry I have added:
$.each(vertices, function(index, item) { vertices[index]['X'] = vertices[index]['x']; vertices[index]['Y'] = vertices[index]['y']; delete vertices[index]['x']; delete vertices[index]['y']; }); if (holes[0]) { for (i = 0; i < holes.length; i++ ) { $.each(holes[i], function(index, item) { holes[i][index]['X'] = holes[i][index]['x']; holes[i][index]['Y'] = holes[i][index]['y']; delete holes[i][index]['x']; delete holes[i][index]['y']; }); } } var scale = 100; ClipperLib.JS.ScaleUpPaths([vertices], scale); if (holes[0]) { ClipperLib.JS.ScaleUpPaths(holes, scale); } vertices = ClipperLib.Clipper.SimplifyPolygons([vertices], ClipperLib.PolyFillType.pftNonZero); // or ClipperLib.PolyFillType.pftEvenOdd if (holes[0]) { holes = ClipperLib.Clipper.SimplifyPolygons(holes, ClipperLib.PolyFillType.pftNonZero); // or ClipperLib.PolyFillType.pftEvenOdd } // var cleandelta = 0.1; // 0.1 should be the appropriate delta in different cases // vertices = ClipperLib.Clipper.CleanPolygons([vertices], cleandelta * scale); // if (holes[0]) { // holes = ClipperLib.Clipper.CleanPolygons(holes, cleandelta * scale); // } ClipperLib.JS.ScaleDownPaths(vertices, scale); if (holes[0]) { ClipperLib.JS.ScaleDownPaths(holes, scale); } for (i = 0; i < vertices.length; i++ ) { $.each(vertices[i], function(index, item) { vertices[i][index]['x'] = vertices[i][index]['X']; vertices[i][index]['y'] = vertices[i][index]['Y']; delete vertices[i][index]['X']; delete vertices[i][index]['Y']; }); } if (holes[0]) { for (i = 0; i < holes.length; i++ ) { $.each(holes[i], function(index, item) { holes[i][index]['x'] = holes[i][index]['X']; holes[i][index]['y'] = holes[i][index]['Y']; delete holes[i][index]['X']; delete holes[i][index]['Y']; }); } }
Now I can see that the vertices are "reduced".
But var faces = ShapeUtils.triangulateShape( vertices, holes ); doesn't generate faces for some examples anymore.
Please can one help how to simplify the shapes correctly?

Triangulation of Polyhedron fails
I am trying to triangulate the faces of a polyhedron using CGAL 4.13 and the following code snippet, which takes a polyhedron definition file in OFF format on stdin:
#include <CGAL/Polyhedron_3.h> #include <CGAL/IO/Polyhedron_iostream.h> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> #include <CGAL/Polygon_mesh_processing/triangulate_faces.h> typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel; typedef CGAL::Polyhedron_3<Kernel> Polyhedron; using namespace std; int main (void) { Polyhedron p; cin >> p; if (!CGAL::Polygon_mesh_processing::triangulate_faces(p)) cerr << p << endl << "Triangulation failed!" << endl; }
However, I observe the following warning:
CGAL warning: check violation! Expression : false File : /usr/include/CGAL/Constrained_triangulation_2.h Line : 902 Explanation: You are using an exact number type, using a Constrained_triangulation_plus_2 class would avoid cascading intersection computation and be much more efficient This message is shown only if CGAL_NO_CDT_2_WARNINGis not defined.
Refer to the bugreporting instructions at https://www.cgal.org/bug_report.html
and the triangulation fails. The message
Triangulation failed!
is printed as well as the polyhedron definition, which clearly shows some faces with 5 or even 7 vertices.Unfortunately the OFF representation of the polyhedron is 8070 lines long, and I failed to create a smaller example to reproduce the issue. So I uploaded it here. It is only available for 30 days there, if someone can suggest a better place to upload it, I will consider that.
After compiling, for example with
g++ O3 tri.cpp o tri lCGAL lgmp lmpfr Wall
the issue can be reproduced with
./tri < poly.off
I am not sure if the failure of the triangulation is related to the warning; how could I use the
Constrained_triangulation_plus_2
class withCGAL::Polygon_mesh_processing::triangulate_faces()
? Is this possible at all? Triangulation of a face is not a complicated thing, how can this fail in the first place? 
Which OpenGL Primitive should I use for draw an triangulation?
I've the following image :
That I was able to triangulate like the following :
I did it using the triangle library of python. My triangulation result is stored into a
dict
object which look like that:>>> triangulation["vertices"] array([[ 23. , 282. ], [ 24. , 254. ], [ 30. , 239. ], [ 43. , 219. ], [ 60. , 204. ], ... And so on ... >>> triangulation["triangles"] array([[ 89, 106, 105], [ 99, 35, 86], [110, 68, 87], [ 47, 66, 83], [ 72, 82, 74], ... And so on ...
Now, I want to distord and draw this texture as a mesh using OpenGL. I was wondering which primitive should I use? I think that
TRIANGLE_STRIP
is the right solution but it's a complex triangulation and it seems obvious that only one TRIANGLE_STRIP will not be enough.