how can I add a box in MATLAB figure which will show average values of the plots? - matlab-figure

I want to add a box in MATLAB figure which contains calculated average value of the plot.I know how to add legend.But, what about showing calculted value from the code?

You may either use an annotation object, or edit the legend string.
View the annotation object documentation here: http://www.mathworks.com/help/matlab/ref/annotation.html
In a nutshell, you can create the annotation object, then modify its content, position, shape, etc programatically using get()/set() on its handles properties.
For example:
x = 1 : 1000;
y1 = sin ( 2 * pi * x ./ 1000 );
y2 = sin ( 2 * pi * x ./ 1000 ) + 0.25;
y1Mean = mean ( y1 );
y2Mean = mean ( y2 );
handleFigure = figure();
handlePlot = plot ( x , y1 , 'b' , x , y2 , 'r' );
handleLegend = legend ( 'y1' , 'y2' );
message1 = [ 'Mean y1 = ' , num2str ( y1Mean ) ];
handleAnnotation = annotation ( 'textbox' , [0.25 0.25 0.1 0.1] , 'string' , message1 );
Creates the following:
You could then change the string in the annotation box using:
message2 = [ 'Mean y2 = ' , num2str ( y2Mean ) ];
set ( handleAnnotation , 'string' , message2 );
Which adjusts the box as follows:
To edit the legend string, simply use the following command:
legendString{1} = [ 'y1 (Mean ' , num2str(y1Mean) , ')' ];
legendString{2} = [ 'y2 (Mean ' , num2str(y2Mean) , ')' ];
set ( handleLegend , 'string' , legendString );
Which adjusts the graph to:

Related

three.js: Calculate faceVertexUvs on custom Geometry for texture mapping

I have this example here:
https://jsfiddle.net/NiklasKnaack/L1cqbdr9/82/
function createPlanetFace( radiusX, radiusY, radiusZ, localUp, resolution ) {
const face = {};
face.geometry = new THREE.Geometry();
face.geometry.faceVertexUvs[ 0 ] = [];
face.verticesOriginal = [];
face.verticesNormalized = [];
const axisA = new THREE.Vector3( localUp.y, localUp.z, localUp.x );
const axisB = new THREE.Vector3().crossVectors( localUp, axisA );
for ( let y = 0; y < resolution; y++ ) {
for ( let x = 0; x < resolution; x++ ) {
const index = x + y * resolution;
const percent = new THREE.Vector2( x, y );
percent.x /= ( resolution - 1 );
percent.y /= ( resolution - 1 );
const vertex = new THREE.Vector3();
vertex.x = ( localUp.x + ( percent.x - 0.5 ) * 2 * axisA.x + ( percent.y - 0.5 ) * 2 * axisB.x ) * radiusX;
vertex.y = ( localUp.y + ( percent.x - 0.5 ) * 2 * axisA.y + ( percent.y - 0.5 ) * 2 * axisB.y ) * radiusY;
vertex.z = ( localUp.z + ( percent.x - 0.5 ) * 2 * axisA.z + ( percent.y - 0.5 ) * 2 * axisB.z ) * radiusZ;
face.verticesOriginal[ index ] = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
vertex.normalize();//create a sphere
vertex.x += vertex.x * radiusX / 2;
vertex.y += vertex.y * radiusY / 2;
vertex.z += vertex.z * radiusZ / 2;
face.verticesNormalized[ index ] = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
face.geometry.vertices[ index ] = vertex;
//if ( index % 6 === 0 && index > 0 && x !== resolution - 1 && y !== resolution - 1 ) {
if ( x !== resolution - 1 && y !== resolution - 1 ) {
const triangle1 = new THREE.Face3( index, index + resolution + 1, index + resolution );
const triangle2 = new THREE.Face3( index, index + 1, index + resolution + 1 );
face.geometry.faces.push( triangle1, triangle2 );
}
}
}
//face.geometry.computeBoundingSphere();
//face.geometry.computeVertexNormals();
//face.geometry.computeFaceNormals();
return face;
};
For this I would like to calculate the UVs so that the loaded texture can be displayed correctly.
In principle, the createPlanetFace function creates a plane. From these 6 planes, a cube or sphere is created. (See it in the example)
So far it already works, only the texture is not displayed because the UVs are missing.
After a lot of research and trying, I get either errors in the console, a totally distorted texture, or just no texture at all. That's why I erased my miserable attempts calculating the UVs.
The examples I have found on this topic are all different. At least most of them. I have now reached a point where I can't get any further and need your help.
Thank you in advance.
Here is a box unwrap I wrote a while ago for regular geometries:
function boxUnwrapUVs(geometry) {
for (var i = 0; i < geometry.faces.length; i++) {
var face = geometry.faces[i];
var faceUVs = geometry.faceVertexUvs[0][i]
var va = geometry.vertices[geometry.faces[i].a]
var vb = geometry.vertices[geometry.faces[i].b]
var vc = geometry.vertices[geometry.faces[i].c]
var vab = new THREE.Vector3().copy(vb).sub(va)
var vac = new THREE.Vector3().copy(vc).sub(va)
//now we have 2 vectors to get the cross product of...
var vcross = new THREE.Vector3().copy(vab).cross(vac);
//Find the largest axis of the plane normal...
vcross.set(Math.abs(vcross.x), Math.abs(vcross.y), Math.abs(vcross.z))
var majorAxis = vcross.x > vcross.y ? (vcross.x > vcross.z ? 'x' : vcross.y > vcross.z ? 'y' : vcross.y > vcross.z) : vcross.y > vcross.z ? 'y' : 'z'
//Take the other two axis from the largest axis
var uAxis = majorAxis == 'x' ? 'y' : majorAxis == 'y' ? 'x' : 'x';
var vAxis = majorAxis == 'x' ? 'z' : majorAxis == 'y' ? 'z' : 'y';
faceUVs[0].set(va[uAxis], va[vAxis])
faceUVs[1].set(vb[uAxis], vb[vAxis])
faceUVs[2].set(vc[uAxis], vc[vAxis])
}
geometry.elementsNeedUpdate = geometry.verticesNeedUpdate = true;
}
Is that helpful?
edit: I rewrote your example because it was too complicated for me to understand...
https://jsfiddle.net/manthrax/dL6kxuf2/1/

How to resize an image by DM scripting?

How to resize an image by DM scripting?
When we process an image, we could resize the image by “process – scale -dimensions -width and height, then change the pixels’ number of width or height “ in DM software.
We also have the option “Constrain proportion” when we resize the image.
How to achieve this by scripting?
Good question.
There are a couple of commands you need. ImageResize() changes the physical size of an image (i.e. the pixel dimensions) while keeping the meta data (tags) and at the same time changing calibration such that the overall field of view remains the same in calibrated units. However, the pixel values are reset to 0 and need to be re-computed in a second step.
The command warp() is used for any mapping with bilinear interpolation of intensity values, so you can use that one for the scaling (plus interpolation).
If you instead want to use "nearest neighbour" interpolation (i.e. copying pixel values), you can most easily achieve this by simple data-copying using the slice2() command for sub-sampling or just the [ ] notation of pixel indexing.
As the thing you are asking for is rather a "basic need" in scripting, the answer to it has actually been included in the F1 help documentation's "examples" section in later GMS versions, so I'm just copy-pasting the script here:
Example 3: Resizing with intensity interpolation
image in, out1, out2
if ( !GetFrontImage( in ) )
Throw( "No image loaded." )
number sx, sy
GetSize( in, sx, sy )
number f = 1.8 // scaling factor
// Variant 1, bi-linear interpolation
out1 := ImageClone( in )
ImageResize( out1, 2, sx * f, sy * f )
out1 = Warp( in, icol / f, irow / f )
SetName( out1, GetName( in ) + " bilinear" )
ShowImage( out1 )
// Variant 2, nearest-neighbor interpolation / sampling
out2 := ImageClone( in )
ImageResize( out2, 2, sx * f, sy * f )
out2 = in[ icol / f, irow / f ]
SetName( out2, GetName( in ) + " nn" )
ShowImage( out2 )
// Note: ImageResize() sets all values to zero and
// adjusts spatial calibration to keep same FOV as before
Now, if you want to constrain the aspect ratio, that would be what you need to do in scripting yourself by making sure you use the same sampling factor in X and Y. If you want to mimic 'User enters finals size' you would do something like this:
image in
if ( !GetFrontImage( in ) )
Throw( "No image loaded." )
number sx = ImageGetDimensionSize( in, 0 )
number sy = ImageGetDimensionSize( in, 1 )
string msg = "Please enter wanted X size."
msg += "\n(Currently: " + sx + " pixels)"
number sx_new
if ( !GetNumber( msg, sx, sx_new) )
exit( 0 )
number f = sx_new/sx
number sy_new = trunc(sx * f)
Result( "\n New Image size: " + sx_new + " x " + sy_new )
image out1 := ImageClone( in )
ImageResize( out1, 2, sx * f, sy * f )
out1 = Warp( in, icol / f, irow / f )
SetName( out1, GetName( in ) + " scaled" )
ShowImage( out1 )

How to explode a 3D model group in ThreeJs?

I have a 3D model , containing many child meshes.
I want to "explode" that mesh ... meaning that every child mesh has to move away from a central point exactly like that thread :
Exploded view algorithm for CAD
To do that , I generate a bounding box of the ancestor mesh , with THREE.Box3 , and compute the center with .getCenter() .
The issue here comes from threeJS's scene graph ...
when setting the position of each child , the whole 3D model does explode when I set it to do so in all directions (XYZ) , but when I choose other combinations like X alone , the explode either bugs and spreads in all directions when it shouldn't, or doesn't explode at all .
Here is the code I am using:
/**
* obj : the current node on the scene graph
* box_ct_world : a vec3 center of the bounding box
*
*/
explode : function(obj , parent , box_ct_world , dif){
var scene = this.el.sceneEl.object3D ; //I am using Aframe , so this is how I retrieve the whole scene .
var object = this.el.object3D ; //same here , this for retrieving the whole 3D model .
var speed = 1 ;
if(obj instanceof THREE.Mesh){
var box_center = box_ct_world ;
var position = obj.position ;
/**
* so this is the beginning of my troubles : I am considering retrieving a world position instead of a local position...
* I have to translate the nodes without the parent matrices interfering .
* The current ligne works the same way as if I retrieved local transformations ... exploding on XYZ , but glitching on the other cases .
*/
position.setFromMatrixPosition(scene.matrixWorld) ;
var addx =0 ;
var addy =0 ;
var addz =0 ;
/**
* This is the vector from the center of the box to the node . we use that to translate every meshes away from the center
*/
if(this.data.X === true){
var addx =(position.x - box_center.x)*this.data.factor *speed ;
}
if(this.data.Y === true){
var addy =(position.y - box_center.y)*this.data.factor *speed;
}
if(this.data.Z === true){
var addz =(position.z - box_center.z)*this.data.factor *speed;
}
var explode_vectorx= addx;
var explode_vectory= addy;
var explode_vectorz= addz;
/**
* this is for making the nodes translate back to their original locations
*/
if(diff < 0 ){
if(explode_vectorx > 0)
explode_vectorx = -explode_vectorx ;
if(explode_vectory > 0)
explode_vectory = -explode_vectory;
if(explode_vectorz > 0)
explode_vectorz = -explode_vectorz;
}
if(diff > 0 ){
if(explode_vectorx < 0)
explode_vectorx = -explode_vectorx ;
if(explode_vectory < 0)
explode_vectory = -explode_vectory;
if(explode_vectorz < 0)
explode_vectorz = -explode_vectorz;
}
var vector = new THREE.Vector3(explode_vectorx , explode_vectory, explode_vectorz) ;
console.log(vector.x+" " + vector.y+ " " + vector.z );
/**
* and here is my biggest problem :
* this function seems to use ancestors matrices
* I need the nodes to move without calling the ancestors matrices , but still keep their original rotation and scale .
*/
obj.position.set(vector.x , vector.y , vector.z ) ;
if(obj.children.length != 0 ){
for(var i = 0 ; i < obj.children.length ; i++){
this.explode(obj.children[i] ,obj, box_ct_world , dif);
}
}
}
else{
if(obj.children.length != 0 )
{
for(var i = 0 ; i < obj.children.length ; i++){
this.explode(obj.children[i] ,obj, box_ct_world , dif);
}
}
}
},
so here is a screenshot using a XYZ explode :
It works pretty fine .
But when using a single axis , like X :
the mesh still goes on all axis as if it was random, when it is supposed to translate only on the X axis .
I think this could be fixed by translating the meshes directly in world space , but I don't know how that can be done in threeJS , especially in that case , because I cannot change the values in matrixWorld (A frame is updating the world matrix every frame I think for these objects , so even if I change any value in the matrixWorld , these will be overriden)
thank you all for your help.

How do you rotate a system of particles (a 2d matrix of size =num_particles*3) so that some entries become zero

So suppose you have a system of particles given by
pos = [x1, y1, z1,
x2, y2, z2,
.
.
xn, yn , zn]
I want to rotate the system so that the first particle will move to the origin, i.e., x1 = 0 , y1 =0 , z1=0, the second particle moves to the z-axis, i.e., new coordinates x2 =0, y2 = 0, z2 = new z2, and finally the third particle moves to the yz plane, i.e., x3=0, y3 = new y3, z3 = new z3. The important thing is that the distance between all particles must preserved.
I tried to use Givens Rotation for zeroing the coordinates I specified above but this method changes the distance between particles. I am coding in Fortran 90.
Added: Here is a subroutine I call it constraint. I tried by building some rotation matrices to rotate the system as I described above. As expected I get the zeros I want. But when I measure the distances between particles after calling constraint, they are not the same as before calling it (Actually what I do is I calculate the energy of the system which is invariant under translation and rotation because it only depends on particles separation)
SUBROUTINE constraint(pos)
REAL(KIND=dp), DIMENSION(np,3), INTENT(INOUT) :: pos
REAL(KIND=dp) :: r1, r2
REAL(KIND=dp), DIMENSION(3,3) :: rotMatrix
!------------------
! Translating the whole system so that the first particle at the origin
IF(pos(1,1) .NE. 0.0d0) THEN
pos(:,1) = pos(:,1) - pos(1,1)
END IF
IF(pos(1,2) .NE. 0.0d0) THEN
pos(:,2) = pos(:,2) - pos(1,2)
END IF
IF(pos(1,3) .NE. 0.0d0) THEN
pos(:,3) = pos(:,3) - pos(1,3)
END IF
! First rotation: Roates the whole system so that the second particle is on
! the z-axis
IF(pos(2,1) .NE. 0.0d0 .OR. pos(2,2) .NE. 0.0d0) THEN
r1 = NORM2(pos(2,:))
r2 = NORM2(pos(2,1:2))
r2 = r2*r2
rotMatrix(1,1) = ( pos(2,2)*pos(2,2) + ( pos(2,1) * pos(2,1) * pos(2,3) ) /r1 ) / r2
rotMatrix(1,2) = pos(2,1)* pos(2,2) * (-1.0d0 + pos(2,3)/r1) / r2
rotMatrix(1,3) = - pos(2,1) / r1
rotMatrix(2,1) = rotMatrix(1,2)
rotMatrix(2,2) = ( pos(2,1)*pos(2,1) + ( pos(2,2) * pos(2,2) * pos(2,3) ) /r1 ) / r2
rotMatrix(2,3) = - pos(2,2) / r1
rotMatrix(3,1) = pos(2,1) / r1
rotMatrix(3,2) = pos(2,2) / r1
rotMatrix(3,3) = pos(2,3) / r1
pos = MATMUL( pos, TRANSPOSE(rotMatrix) )
END IF
! Second rotation: Roates the whole system around the z-axis so that the
! third particle is on the zy-plane
! the z-axis
IF( pos(3,1) .NE. 0.0d0 ) THEN
r1 = NORM2(pos(3,1:2))
rotMatrix(1,1) = pos(3,2) / r1
rotMatrix(1,2) = - pos(3,1) / r1
rotMatrix(1,3) = 0.0d0
rotMatrix(2,1) = pos(3,1) / r1
rotMatrix(2,2) = - pos(3,2) / r1
rotMatrix(2,3) = 0.0d0
rotMatrix(3,1) = 0.0d0
rotMatrix(3,2) = 0.0d0
rotMatrix(3,3) = 1.0d0
pos = MATMUL( pos, TRANSPOSE(rotMatrix) )
END IF
END SUBROUTINE constraint
While I was writing the answer, you have included your code, which seems to be based on rigid-body rotation. Because my code below is also based on rigid-body rotation, I will skip detailed explanations; so please compare the two codes if necessary (FYI, in my case, I perform sequential Rz -> Ry -> Rz rotations, as defined by the Euler angles).
program rotation
implicit none
integer, parameter :: N = 10, x=1, y=2, z=3
real, parameter :: pi = acos(-1.0)
real :: pos( 3, N ), alpha, beta, gamma, phi, ref( 3 ), rot(3,3)
integer i
!> Initial coordinates.
do i = 1, N
phi = 2.0 * pi / N * (i - 1)
pos( :, i ) = [ cos( phi ), sin( phi ), 0. ] &
* ( 3.0 + 2.0 * mod(i,2) ) * 0.55
enddo
pos(2,:) = pos(2,:) + 5.0
!> Translate the system such that pos(:,1) = 0.
ref(:) = pos( :, 1 )
do i = 1, N
pos( :, i ) = pos( :, i ) - ref(:)
enddo
!> Get the polar coordinates of pos(:, 2).
beta = acos( pos( z, 2 ) / norm2( pos(:, 2) ) ) !! in [0,pi]
alpha = atan2( pos( y, 2 ), pos( x, 2 ) ) !! in [-pi,pi]
!> Apply Rz( -alpha ).
pos = matmul( get_Rz( -alpha ), pos )
!> Apply Ry( -beta ).
pos = matmul( get_Ry( -beta ), pos )
!> Get the azimuthal angle of pos(:, 3).
gamma = atan2( pos( y, 3 ), pos( x, 3 ) )
!> Apply Rz( -gamma + pi/2 ).
pos = matmul( get_Rz( -gamma + pi/2 ), pos )
!> Result.
print *, "new coord:"
do i = 1, N
print "(3f10.5)", pos( :, i )
enddo
rot = matmul( get_Rz( -gamma + pi/2 ), &
matmul( get_Ry( -beta ), get_Rz( -alpha ) ) )
print *, "full rotational matrix (to be applied after translation):"
do i = 1, 3
print "(3f10.5)", rot( i, : )
enddo
contains
function get_Rz( ang ) result( R )
real :: ang, R(3,3)
R( 1, : ) = [ cos( ang ), -sin( ang ), 0. ]
R( 2, : ) = [ sin( ang ), cos( ang ), 0. ]
R( 3, : ) = [ 0., 0., 1. ]
endfunction
function get_Ry( ang ) result( R )
real :: ang, R(3,3)
R( 1, : ) = [ cos( ang ), 0., sin( ang ) ]
R( 2, : ) = [ 0., 1., 0. ]
R( 3, : ) = [ -sin( ang ), 0., cos( ang ) ]
endfunction
endprogram
EDIT
Rewriting the rotation matrices in terms of Cartesian coordinates gives
!> Apply Ry( -beta ) * Rz( -alpha ).
p(:) = pos( :, 2 )
r1 = norm2( p(:) )
L = norm2( p( 1:2 ) )
Lr = L * r1
rot( 1, : ) = [ p(z)*p(x) / Lr, p(z)*p(y) / Lr, - L / r1 ]
rot( 2, : ) = [ - p(y) / L, p(x) / L, 0. ]
rot( 3, : ) = [ p(x) / r1, p(y) / r1, p(z) / r1 ]
pos = matmul( rot, pos )
!> Apply Rz( -gamma + pi/2 ).
p(:) = pos( :, 3 )
L = norm2( p( 1:2 ) )
rot( 1, : ) = [ p(y) / L, p(x) / L, 0. ]
rot( 2, : ) = [ -p(x) / L, p(y) / L, 0. ]
rot( 3, : ) = [ 0., 0., 1. ]
pos = matmul( rot, pos )
Not sure about extending it to the nth point but for the 1st 3 going by your ordering:
new p1 = (0,0,0) - given
new p2 = (0,0,dist(p1,p2))
new p3 = (0,sin(A)*dist(p1,p3),cos(A)*dist(p1,p3))
where A is the angle between the sides p1-p3 and p1-p2 which can be found using law of cosines (since you have the length in between all 3 points):
A =
arccos((dist(1,3)*dist(1,3)+dist(1,2)*dist(1,2)-dist(2,3)*dist(2,3))/ (2*dist(1,3)*dist(1,2)))
Looks my origional answer was deleted... consider changing your code to:
! Translating the whole system so that the first particle at the origin
TransX = pos(1,1)
TransY = pos(1,2)
TransZ = pos(1,3)
IF(pos(1,1) .NE. 0.0d0) THEN
pos(:,1) = pos(:,1) - TransX
END IF
IF(pos(1,2) .NE. 0.0d0) THEN
pos(:,2) = pos(:,2) - TransY
END IF
IF(pos(1,3) .NE. 0.0d0) THEN
pos(:,3) = pos(:,3) - TransZ
END IF

OpenGL : Draw curve between 3 points

Basically I wish to draw a curve between 3 points in openGL as the below image indicates. I've found a couple of segments of code which would be useful for drawing a bezier curve using 4 points but for 3 points I've had really no success.
From the definition of a Bezier curve you have the following formula (for each x, y component):
x(t) = (1-t)^3*p1x + 3*t*(1-t)^2*c1x + 3*t^2*(1-t)*c3x + t^3*p3x
y(t) = (1-t)^3*p1y + 3*t*(1-t)^2*c1y + 3*t^2*(1-t)*c3y + t^3*p3y
In your case you know the mid point (p2x,p2y). You can also assume that c1x and c2x have the same value; and that c1y and c2y also have the same value
So we have the following equations at t=0.5
p2x = (3/4)*c1x+(p1x+p3x)/8
p2y = (3/4)*c1y+(p1y+p3y)/8
which are solved for c1x=c2x and c1y=c2y with
c1x = c2x = -(p1x-8*p2x+p3x)/6
c1y = c2y = -(p1y-8*p2y+p3y)/6
to give the final Bezier equation to use in terms of points (p1x,p1y), (p2x,p2y) and (p3x,p3y):
x(t) = (1-t)^3 * [p1x]
+ 3*t*(1-t)^2 * [-(p1x-8*p2x+p3x)/6]
+ 3*t^2*(1-t) * [-(p1x-8*p2x+p3x)/6]
+ t^3 * [p3x]
y(t) = (1-t)^3 * [p1y]
+ 3*t*(1-t)^2 * [-(p1y-8*p2y+p3y)/6]
+ 3*t^2*(1-t) * [-(p1y-8*p2y+p3y)/6]
+ t^3 * [p3y]
Summary
Try the four control points
( p1x, p1y )
( -(p1x-8*p2x+p3x)/6, -(p1y-8*p2y+p3y)/6 )
( -(p1x-8*p2x+p3x)/6, -(p1y-8*p2y+p3y)/6 )
( p3x, p3y )
Here is an example I made with p1=(0,0), p2=(2,2) and p3=(4,-1). I calculated the following control points
( 0, 0 )
( 2, 17/6 )
( 2, 17/6 )
( 4, -1)
with the results shown below:
Sounds like you want a Hermite spline.

Resources