Rotating matrices in simulink - matlab

I want to create in Simulink, a homogenous matrix in order to simulate the rotation and translation of an object in space.
How can I create a 4x4 matrix which will take as input the angle given?
For example a translation across the X axes combined with a rotation in Z would be in MATLAB:
%Supposing the input is
in = [a, b]
%translational part:
transl = eye(4);
transl (1,4) = in(1);
%Rotational Part:
rotat = eye(4);
rotat(1:3,1:3) = rotx(in(2));
move = transl*rotat;
The main problem is that I would like the Simulink model to be the more code-free (without MATLAB interpreted functions etc), just blocks.
Thank you.

First off, sometimes code is the better way to accomplish something. Some things are needlessly complicated when done as signal processing.
A Vector Concatenate can be used to generate a vector, which in turn can be fed into a Matrix Concatenate to create a matrix. Both blocks are found under Math Operations. There you should also find all methods necessary to multiply it with the given values, etc.

Try the 'Rotation Angles to Direction Cosine Matrix' block. It converts rotation angles to direction cosine matrix. The output is a 3x3 matrix, Rxyz, that performs coordinate transformations based on rotation angles from body frame to earth frame.

Related

How to take Fourier transforms wrt arbitrary variables?

I want to take FFT of following forms:
Fourier in spherical coordinates
So in fact, my f(theta,phi) is a 3D image voxel, ie it has f(radius,theta,phi). If I had to take integral along dx, that would amount to just selecting my IMG(ylocation,:,zlocation)=currentvoxel and running fft(currentvoxel) on it. However, now I have to only take fft along phi. Which is hard because it requires for me to find all the locations with theta=currenttheta and for each r=currentr, I have to find all the phi's to take fft.
I don't even know how to unroll the phi to take fft. When it's Cartesian coordinates, it's easy, just start from x=0,..x=end and run fft. Is phi case the same? Get all the phi's on a certain r,theta and sort them 0 to 2pi and take fft?
Or maybe sine/cosine transforms like this:
cosine/sine transform
If this was a f(x,y), I think the way to do this in MATLAB would be to take dct(f*(x.^2+y.^2)). In other words running a discrete cosine transform. Am I right?
Extra clarification on second part:
The integral I'm interested in is: bessel
where j_l(kr): expanded j_l
and
expanded further
finally the F_(l)(t) is given by previous: cosine/sine transform

matlab: cdfplot of relative error

The figure shown above is the plot of cumulative distribution function (cdf) plot for relative error (attached together the code used to generate the plot). The relative error is defined as abs(measured-predicted)/(measured). May I know the possible error/interpretation as the plot is supposed to be a smooth curve.
X = load('measured.txt');
Xhat = load('predicted.txt');
idx = find(X>0);
x = X(idx);
xhat = Xhat(idx);
relativeError = abs(x-xhat)./(x);
cdfplot(relativeError);
The input data file is a 4x4 matrix with zeros on the diagonal and some unmeasured entries (represent with 0). Appreciate for your kind help. Thanks!
The plot should be a discontinuous one because you are using discrete data. You are not plotting an analytic function which has an explicit (or implicit) function that maps, say, x to y. Instead, all you have is at most 16 points that relates x and y.
The CDF only "grows" when new samples are counted; otherwise its value remains steady, just because there isn't any satisfying sample that could increase the "frequency".
You can check the example in Mathworks' `cdfplot1 documentation to understand the concept of "empirical cdf". Again, only when you observe a sample can you increase the cdf.
If you really want to "get" a smooth curve, either 1) add more points so that the discontinuous line looks smoother, or 2) find any statistical model of whatever you are working on, and plot the analytic function instead.

Matlab plot function defined on a complex coordinate

I would like to plot some figures like this one:
-axis being real and imag part of some complex valued vector(usually either pure real or imag)
-have some 3D visualization like in the given case
First, define your complex function as a function of (Re(x), Im(x)). In complex analysis, you can decompose any complex function into its real parts and imaginary parts. In other words:
F(x) = Re(x) + i*Im(x)
In the case of a two-dimensional grid, you can obviously extend to defining the function in terms of (x,y). In other words:
F(x,y) = Re(x,y) + i*Im(x,y)
In your case, I'm assuming you'd want the 2D approach. As such, let's use I and J to represent the real parts and imaginary parts separately. Also, let's start off with a simple example, like cos(x) + i*sin(y) which is based on the very popular Euler exponential function. It isn't exact, but I modified it slightly as the plot looks nice.
Here are the steps you would do in MATLAB:
Define your function in terms of I and J
Make a set of points in both domains - something like meshgrid will work
Use a 3D visualization plot - You can plot the individual points, or plot it on a surface (like surf, or mesh).
NB: Because this is a complex valued function, let's plot the magnitude of the output. You were pretty ambiguous with your details, so let's assume we are plotting the magnitude.
Let's do this in code line by line:
% // Step #1
F = #(I,J) cos(I) + i*sin(J);
% // Step #2
[I,J] = meshgrid(-4:0.01:4, -4:0.01:4);
% // Step #3
K = F(I,J);
% // Let's make it look nice!
mesh(I,J,abs(K));
xlabel('Real');
ylabel('Imaginary');
zlabel('Magnitude');
colorbar;
This is the resultant plot that you get:
Let's step through this code slowly. Step #1 is an anonymous function that is defined in terms of I and J. Step #2 defines I and J as matrices where each location in I and J gives you the real and imaginary co-ordinates at their matching spatial locations to be evaluated in the complex function. I have defined both of the domains to be between [-4,4]. The first parameter spans the real axis while the second parameter spans the imaginary axis. Obviously change the limits as you see fit. Make sure the step size is small enough so that the plot is smooth. Step #3 will take each complex value and evaluate what the resultant is. After, you create a 3D mesh plot that will plot the real and imaginary axis in the first two dimensions and the magnitude of the complex number in the third dimension. abs() takes the absolute value in MATLAB. If the contents within the matrix are real, then it simply returns the positive of the number. If the contents within the matrix are complex, then it returns the magnitude / length of the complex value.
I have labeled the axes as well as placed a colorbar on the side to visualize the heights of the surface plot as colours. It also gives you an idea of how high and how long the values are in a more pleasing and visual way.
As a gentle push in your direction, let's take a slice out of this complex function. Let's make the real component equal to 0, while the imaginary components span between [-4,4]. Instead of using mesh or surf, you can use plot3 to plot your points. As such, try something like this:
F = #(I,J) cos(I) + i*sin(J);
J = -4:0.01:4;
I = zeros(1,length(J));
K = F(I,J);
plot3(I, J, abs(K));
xlabel('Real');
ylabel('Imaginary');
zlabel('Magnitude');
grid;
plot3 does not provide a grid by default, which is why the grid command is there. This is what I get:
As expected, if the function is purely imaginary, there should only be a sinusoidal contribution (i*sin(y)).
You can play around with this and add more traces if you need to.
Hope this helps!

Sampling uniformly from many circles on the sphere efficiently in matlab

I have a 3-by-N matrix X whose columns are vectors on the unit sphere (i.e., the Euclidean length of each vector is 1), and I have a 1-by-N vector Theta whose entries are all angles between 0 and pi. For each i, there is a circle on the sphere centered at X(:,i) defined as the set of all points that have the angle Theta(i) with X(:,i). I would like to get one uniform sample from the circle for each i, avoiding for loops because they can be slow in Matlab. I know that in vectorized Matlab code I can easily get one sample each from all circles with angles in Theta if I assume the center of all circles is [0,0,1], and then I know how to get a rotation matrix (using Rodrigues rotation formula) that rotates [0,0,1] to another desired vector x, so for each i, I can just apply this rotation matrix to the sample point I obtained assuming [0,0,1] was the center.
I would like to this for all i without for loops, i.e. using array/matrix/vector notation.
If you're using Rodrigues' rotation formula, you're trying to convert from axis-angle representation to rotation matrices. You're in luck. I happen to have written fast vectorized code to do exactly what I believe you're asking about. You can can find the code here: axang2rotmat.m. Use is pretty straightforward (read the help):
n = 1e3; % Number of axis-angles and rotation matrices
th = pi*rand(1,n); % Random rotation angles between 0 and pi
v = normc(rand(3,n)); % Random rotation vectors, normalized across columns
R = axang2rotmat(v,th); % Generate n rotation matrices, R is 3-by-3-n
Note, the above code is just to demonstrate the use of axang2rotmat and won't give you uniformly sampled rotation matrices (See Miles, Biometrika 1962 for details on why and workaround). I recommend that you calculate random rotation matrices directly, however. You can us another of my functions for that: randrotmat.m.
I also have code to convert back from rotation matrices to axis-angle and check if a particular matrix is a rotation matrix here.

How to use matlab contourf to draw two-dimensional decision boundary

I finished an SVM training and got data like X, Y. X is the feature matrix only with 2 dimensions, and Y is the classification labels. Because the data is only in two dimensions, so I would like to draw a decision boundary to show the surface of support vectors.
I use contouf in Matlab to do the trick, but really find it hard to understand how to use the function.
I wrote like:
#1 try:
contourf(X);
#2 try:
contourf([X(:,1) X(:,2) Y]);
#3 try:
Z(:,:,1)=X(Y==1,:);
Z(:,:,2)=X(Y==2,:);
contourf(Z);
all these things do not correctly. And I checked the Matlab help files, most of them make Z as a function, so I really do not know how to form the correct Z matrix.
If you're using the svmtrain and svmclassify commands from Bioinformatics Toolbox, you can just use the additional input argument (...'showplot', true), and it will display a scatter plot with a decision boundary and the support vectors highlighted.
If you're using your own SVM, or a third-party tool such as libSVM, what you probably need to do is to:
Create a grid of points in your 2D input feature space using the meshgrid command
Classify those points using your trained SVM
Plot the grid of points and the classifications using contourf.
For example, in kind-of-MATLAB-but-pseudocode, assuming your input features are called X1 and X2:
numPtsInGrid = 100;
x1Range = linspace(x1lower, x1upper, numPtsInGrid);
x2Range = linspace(x2lower, x2upper, numPtsInGrid);
[X1, X2] = meshgrid(x1Range, x2Range);
Z = classifyWithMySVMSomehow([X1(:), X2(:)]);
contourf(X1(:), X2(:), Z(:))
Hope that helps.
I know it's been a while but I will give it a try in case someone else will come up with that issue.
Assume we have a 2D training set so as to train an SVM model, in other words the feature space is a 2D space. We know that a kernel SVM model leads to a score (or decision) function of the form:
f(x) = sumi=1 to N(aiyik(x,xi)) + b
Where N is the number of support vectors, xi is the i -th support vector, ai is the estimated Lagrange multiplier and yi the associated class label. Values(scores) of decision function in way depict the distance of the observation x frοm the decision boundary.
Now assume that for every point (X,Y) in the 2D feature space we can find the corresponding score of the decision function. We can plot the results in the 3D euclidean space, where X corresponds to values of first feature vector f1, Y to values of second feature f2, and Z to the the return of decision function for every point (X,Y). The intersection of this 3D figure with the Z=0 plane gives us the decision boundary into the two-dimensional feature space. In other words, imagine that the decision boundary is formed by the (X,Y) points that have scores equal to 0. Seems logical right?
Now in MATLAB you can easily do that, by first creating a grid in X,Y space:
d = 0.02;
[x1Grid,x2Grid] = meshgrid(minimum_X:d:maximum_X,minimum_Y:d:maximum_Y);
d is selected according to the desired resolution of the grid.
Then for a trained model SVMModel find the scores of every grid's point:
xGrid = [x1Grid(:),x2Grid(:)];
[~,scores] = predict(SVMModel,xGrid);
Finally plot the decision boundary
figure;
contour(x1Grid,x2Grid,reshape(scores(:,2),size(x1Grid)),[0 0],'k');
Contour gives us a 2D graph where information about the 3rd dimension is depicted as solid lines in the 2D plane. These lines implie iso-response values, in other words (X,Y) points with same Z value. In our occasion contour gives us the decision boundary.
Hope I helped to make all that more clear. You can find very useful information and examples in the following links:
MATLAB's example
Representation of decision function in 3D space