If I have a 3D matrix, X that is 4 x 10 x 50.
The matrix consists of positions and velocities in the first dimension, different particles (or boats or whatever) indexes in the second and lastly the different time steps for the particles movement in the third. Maybe not that important but maybe it clarifies my problem.
Say I want to plot the values of X for specific indices in the first two dimensions across the 3rd dimension
>> plot(X(1,1,:))
Error using plot
Data may not have more than 2 dimensions
Even though the values supplied are one dimensional I cant use plot here because they are given separately like this:
>> X(1,1,1:5)
ans(:,:,1) =
10
ans(:,:,2) =
11.4426
ans(:,:,3) =
12.5169
ans(:,:,4) =
13.7492
ans(:,:,5) =
14.9430
How can I convert the result of X( 1, 1, :) into a vector?
Indexing into X with X( 1, 1, : ) returns a 3D matrix. However, plot requires its input to be a vector or 2D matrix. To convert X( 1, 1, : ) to vector you need to remove the singleton dimensions. The builtin function squeeze does this:
Try:
X2 = squeeze( X( 1, 1, : ) );
plot( X2 )
The way you are indexing it actually yields a 2-d vector. So size(A(:,:,1) is actually 4x10.
To plot it, use Matlab's squeeze operator
plot(squeeze(X(:,:,1))
Related
This question already has an answer here:
Plotting volumetric data in MATLAB
(1 answer)
Closed 4 years ago.
I have given a 300x300x300 Matrix.
The first subscript represents the x-value, the second the y-value and the third the z-value.
To access a value of a specific point in the matrix i use:
matrix(x-val, y-val, z-val)
I want to create a 3D scatter plot where the color of the dots in the plot changes based on the values of the points in the matrix. All values are >=0
As i am pretty new to Matlab i have no idea where to start.
MathWorks has a page that summarizes types of MATLAB plots. I've referenced it on multiple occasions. The function you are looking for is scatter3(X,Y,Z,S,C). Walk through the function's example, it should help you out.
I'm not sure how you can have a 300x300x300 matrix for a point cloud in 3-D. I will assume you have a 300x300x3 matrix, i.e.:
x = matrix(:,:,1);
y = matrix(:,:,2);
z = matrix(:,:,3);
First of all, you probably want to rearrange points into a 2D matrix:
m = reshape(matrix, numel(matrix(:,:,1), 3);
n = size(m,1);
Your matrix is now arranged as a n-by-3 matrix, coloumn 1, 2 and 3 representing x-, y- and z-axis respectively, i.e.:
m = [ x1 y1 z1]
[ x2 y2 z2]
[ ... ]
[ xn yn zn]
Then you can create a basic 3D scatter plot:
scatter3(m(:,1), m(:,2), m(:,3))
However, this is not what you want, because points are in the same colour. To add colour based on your colouring logic, you should firstly create a color matrix using one of the MATLAB's built-in color maps. Here I use jet:
myc = jet(n);
You can also create your own colour map ofc. Elements in the colour matrix are simply normalised rgb values.
Now you will have to weight each points using your own logic:
weighting = myWeightingLogic(m);
weighting will be a n-by-1 vector and it should be normalised if it is not yet.
weighting = weighting/max(weighting);
Now you can colour your scatter plot:
scatter3(m(:,1), m(:,2), m(:,3)), [], myc(round(weighting*n),:));
The full code:
m = reshape(matrix, numel(matrix(:,:,1), 3);
n = size(m,1);
myc = jet(n);
weighting = myWeightingLogic(m);
weighting = weighting/max(weighting);
scatter3(m(:,1), m(:,2), m(:,3)), [], myc(round(weighting*n),:));
I have a 3D matrix:
A = [5 7 8; 0 1 9; 4 3 6];
A(:,:,2) = [1 0 4; 3 5 6; 9 8 7]
I want to apply a 3D FFT in this matrix using decomposition of 1D FFT. I read that it I should apply 1D FFT in each dimension.
How can I do this?
For x and y, I do this:
for k=0:2
y1 = A(:,k+1,:);
A(:,k+1,:) = fft(y1);
end
for k=0:2
y2 = A(k+1,:,:);
A(k+1,:,:) = fft(y2);
end
For the dimension z, I don't know how to do this.
The fft function accepts a third input specifiying dimension, and is vectorized with respect to the other dimensions. So you can simply use:
result = fft(fft(fft(A, [], 1), [], 2), [], 3);
First, your loops should look like this:
for k=1:size(A,2)
y = A(:,k,:);
A(:,k,:) = fft(y);
end
Second, the loop above is identical to (as #Luis Mendo said in his answer):
A = fft(A,[],2);
There is no need to write a loop at all.
Third, to compute the 1D FFT along the 3rd dimension, you use:
fft(A,[],3);
You could write this as a loop (just to answer your explicit question, I don't recommend you do this):
for k=1:size(A,3)
y = A(:,:,k);
A(:,:,k) = fft(y);
end
If, for some reason, that doesn't work in your version of MATLAB because of the shape of y, you can reshape y to be a column vector:
... fft(y(:));
Finally, to compute the 3D FFT using 1D decompositions, you can simply write
A = fftn(A);
This follows the exact same process you are trying to implement, except it does it much faster.
Let us have a 4D matrix (tensor), output:
[X,Y,Z] = ndgrid(-50:55,-55:60,-50:60);
a = 1:4;
output = zeros([size(X),length(a)]);
Next, we determine the area inside the ellipsoid:
position = [0,0,0];
radius = [10,20,10];
test_func = #(X,Y,Z) ((X-position(1))/radius(1)).^2 ...
+ ((Y-position(2))/radius(2)).^2 ...
+ ((Z-position(3))/radius(3)).^2 <= 1;
condition = test_func(X,Y,Z);
I need to fill the matrix output inside the ellipsoid for the first 3 dimensions. But for the fourth dimension I need to fill a. I need to do something like this:
output(condition,:) = a;
But it does not work. How to do it? Any ideas please!
If I understand your question correctly, you have a 4D matrix where each temporal blob of pixels in 3D for each 4D slice is filled with a number... from 1 up to 4 where each number tells you which slice you're in.
You can cleverly use bsxfun and permute to help you accomplish this task:
output = bsxfun(#times, double(condition), permute(a, [1 4 3 2]));
This takes a bit of imagination to imagine how this works but it's quite simple. condition is a 3D array of logical values where each location in this 3D space is either 0 if it doesn't or 1 if it does belong to a point inside an ellipsoid. a is a row vector from 1 through 4 or however many elements you want this to end with. Let's call this N to be more general.
permute(a, [1 4 3 2]) shuffles the dimensions such that we create a 4D vector where we have 1 row, 1 column and 1 slice but we have 4 elements going into the fourth dimension.
By using bsxfun in this regard, it performs automatic broadcasting on two inputs where each dimension in the output array will match whichever of the two inputs had the largest value. The condition is that for each dimension independently, they should both match or one of them is a singleton dimension (i.e. 1).
Therefore for your particular example, condition will be 106 x 116 x 111 while the output of the permute operation will be 1 x 1 x 1 x N. condition is also technically 106 x 116 x 111 x 1 and using bsxfun, we would thus get an output array of size 106 x 116 x 111 x N. Performing the element-wise #times operation, the permuted vector a will thus broadcast itself over all dimensions where each 3D slice i will contain the value of i. The condition matrix will then duplicate itself over the fourth dimension so we have N copies of the condition matrix, and performing the element-wise multiply thus completes what you need. This is doable as the logical mask you created contains only 0s and 1s. By multiplying element-wise with this mask, only the values that are 1 will register a change. Specifically, if you multiply the values at these locations by any non-zero value, they will change to these non-zero values. Using this logic, you'd want to make these values a. It is important to note that I had to cast condition to double as bsxfun only allows two inputs of the same class / data type to be used.
To visually see that this is correct, I'll show scatter plots of each blob where the colour of each blob would denote what label in a it belongs to:
close all;
N = 4;
clrs = 'rgbm';
figure;
for ii = 1 : N
blob = output(:,:,:,ii);
subplot(2,2,ii);
plot3(X(blob == ii), Y(blob == ii), Z(blob == ii), [clrs(ii) '.']);
end
We get:
Notice that the spatial extent of each ellipsoid is the same but what is different are the colours assigned to each blob. I've made it such that the values for the first blob, or those assigned to a = 1 are red, those that are assigned to a = 2 are assigned to green, a = 3 to blue and finally a = 4 to magenta.
If you absolutely want to be sure that the coordinates of each blob are equal across all blobs, you can use find in each 3D blob individually and ensure that the non-zero indices are all equal:
inds = arrayfun(#(x) find(output(:,:,:,x)), a, 'un', 0);
all_equal = isequal(inds{:});
The code finds in each blob the column major indices of all non-zero locations in 3D. To know whether or not we got it right, each 3D blob should all contain the same non-zero column major indices. The arrayfun call goes through each 3D blob and returns a cell array where each cell element is the column major indices for a particular blob. We then pipe this into isequal to ensure that all of these column major indices arrays are equal. We get:
>> all_equal
all_equal =
1
I have two images which one of them is the Original image and the second one is Transformed image.
I have to find out how many degrees Transformed image was rotated using 3x3 transformation matrix. Plus, I need to find how far translated from origin.
Both images are grayscaled and held in matrix variables. Their sizes are same [350 500].
I have found a few lecture notes like this.
Lecture notes say that I should use the following matrix formula for rotation:
For translation matrix the formula is given:
Everything is good. But there are two problems:
I could not imagine how to implement the formulas using MATLAB.
The formulas are shaped to find x',y' values but I already have got x,x',y,y' values. I need to find rotation angle (theta) and tx and ty.
I want to know the equivailence of x, x', y, y' in the the matrix.
I have got the following code:
rotationMatrix = [ cos(theta) sin(theta) 0 ; ...
-sin(theta) cos(theta) 0 ; ...
0 0 1];
translationMatrix = [ 1 0 tx; ...
0 1 ty; ...
0 0 1];
But as you can see, tx, ty, theta variables are not defined before used. How can I calculate theta, tx and ty?
PS: It is forbidden to use Image Processing Toolbox functions.
This is essentially a homography recovery problem. What you are doing is given co-ordinates in one image and the corresponding co-ordinates in the other image, you are trying to recover the combined translation and rotation matrix that was used to warp the points from the one image to the other.
You can essentially combine the rotation and translation into a single matrix by multiplying the two matrices together. Multiplying is simply compositing the two operations together. You would this get:
H = [cos(theta) -sin(theta) tx]
[sin(theta) cos(theta) ty]
[ 0 0 1]
The idea behind this is to find the parameters by minimizing the error through least squares between each pair of points.
Basically, what you want to find is the following relationship:
xi_after = H*xi_before
H is the combined rotation and translation matrix required to map the co-ordinates from the one image to the other. H is also a 3 x 3 matrix, and knowing that the lower right entry (row 3, column 3) is 1, it makes things easier. Also, assuming that your points are in the augmented co-ordinate system, we essentially want to find this relationship for each pair of co-ordinates from the first image (x_i, y_i) to the other (x_i', y_i'):
[p_i*x_i'] [h11 h12 h13] [x_i]
[p_i*y_i'] = [h21 h22 h23] * [y_i]
[ p_i ] [h31 h32 1 ] [ 1 ]
The scale of p_i is to account for homography scaling and vanishing points. Let's perform a matrix-vector multiplication of this equation. We can ignore the 3rd element as it isn't useful to us (for now):
p_i*x_i' = h11*x_i + h12*y_i + h13
p_i*y_i' = h21*x_i + h22*y_i + h23
Now let's take a look at the 3rd element. We know that p_i = h31*x_i + h32*y_i + 1. As such, substituting p_i into each of the equations, and rearranging to solve for x_i' and y_i', we thus get:
x_i' = h11*x_i + h12*y_i + h13 - h31*x_i*x_i' - h32*y_i*x_i'
y_i' = h21*x_i + h22*y_i + h23 - h31*x_i*y_i' - h32*y_i*y_i'
What you have here now are two equations for each unique pair of points. What we can do now is build an over-determined system of equations. Take each pair and build two equations out of them. You will then put it into matrix form, i.e.:
Ah = b
A would be a matrix of coefficients that were built from each set of equations using the co-ordinates from the first image, b would be each pair of points for the second image and h would be the parameters you are solving for. Ultimately, you are finally solving this linear system of equations reformulated in matrix form:
You would solve for the vector h which can be performed through least squares. In MATLAB, you can do this via:
h = A \ b;
A sidenote for you: If the movement between images is truly just a rotation and translation, then h31 and h32 will both be zero after we solve for the parameters. However, I always like to be thorough and so I will solve for h31 and h32 anyway.
NB: This method will only work if you have at least 4 unique pairs of points. Because there are 8 parameters to solve for, and there are 2 equations per point, A must have at least a rank of 8 in order for the system to be consistent (if you want to throw in some linear algebra terminology in the loop). You will not be able to solve this problem if you have less than 4 points.
If you want some MATLAB code, let's assume that your points are stored in sourcePoints and targetPoints. sourcePoints are from the first image and targetPoints are for the second image. Obviously, there should be the same number of points between both images. It is assumed that both sourcePoints and targetPoints are stored as M x 2 matrices. The first columns contain your x co-ordinates while the second columns contain your y co-ordinates.
numPoints = size(sourcePoints, 1);
%// Cast data to double to be sure
sourcePoints = double(sourcePoints);
targetPoints = double(targetPoints);
%//Extract relevant data
xSource = sourcePoints(:,1);
ySource = sourcePoints(:,2);
xTarget = targetPoints(:,1);
yTarget = targetPoints(:,2);
%//Create helper vectors
vec0 = zeros(numPoints, 1);
vec1 = ones(numPoints, 1);
xSourcexTarget = -xSource.*xTarget;
ySourcexTarget = -ySource.*xTarget;
xSourceyTarget = -xSource.*yTarget;
ySourceyTarget = -ySource.*yTarget;
%//Build matrix
A = [xSource ySource vec1 vec0 vec0 vec0 xSourcexTarget ySourcexTarget; ...
vec0 vec0 vec0 xSource ySource vec1 xSourceyTarget ySourceyTarget];
%//Build RHS vector
b = [xTarget; yTarget];
%//Solve homography by least squares
h = A \ b;
%// Reshape to a 3 x 3 matrix (optional)
%// Must transpose as reshape is performed
%// in column major format
h(9) = 1; %// Add in that h33 is 1 before we reshape
hmatrix = reshape(h, 3, 3)';
Once you are finished, you have a combined rotation and translation matrix. If you want the x and y translations, simply pick off column 3, rows 1 and 2 in hmatrix. However, we can also work with the vector of h itself, and so h13 would be element 3, and h23 would be element number 6. If you want the angle of rotation, simply take the appropriate inverse trigonometric function to rows 1, 2 and columns 1, 2. For the h vector, this would be elements 1, 2, 4 and 5. There will be a bit of inconsistency depending on which elements you choose as this was solved by least squares. One way to get a good overall angle would perhaps be to find the angles of all 4 elements then do some sort of average. Either way, this is a good starting point.
References
I learned about homography a while ago through Leow Wee Kheng's Computer Vision course. What I have told you is based on his slides: http://www.comp.nus.edu.sg/~cs4243/lecture/camera.pdf. Take a look at slides 30-32 if you want to know where I pulled this material from. However, the MATLAB code I wrote myself :)
I have a problem in constructing a vector from an image. I had used a 512 x 512 colour image and separated the rgb planes. Now i want to convert these three planes into three 1D vectors which should be as given in the following example.
Consider a 4x4x3 matrix. Converting it into RGB planes is easy. Now I need to convert these three planes into 1D vectors as given below
V=[r1g1b1....r6]
W=[g6b6r7...g11]
X=[b11r12...B16]
The program ive written is as follows. I used the reshape function to convert RGB planes into 1D vectors. Now I have trouble in regrouping them into different vectors.
A=imread('C:\Users\Desktop\lena.jpg');
% Extract the individual red, green, and blue color channels.
R = A(:, :, 1);
G = A(:, :, 2);
B = A(:, :, 3);
R1 = reshape(R.',1,[]);
G1 = reshape(G.',1,[]);
B1 = reshape(B.',1,[]);
I had converted the 2D matrices R G and B into 1D vectors R1, G1 and B1. Now I just need to create new vectores with all three values.I have no idea how to proceed...Please do help...Thanks in advance.
OK, given your example, what you want to do is given a RGB image, you want to separate the image into 3 vectors such that the RGB components are interleaved. This can easily be achieved by a permutation of the dimensions first. What you can do specifically is:
B = permute(A, [3 1 2]);
What permute does is that it rearranges the dimensions so that it produces another matrix. Specifically, what we're going to do is we are going to take each value in the third dimension and make them appear in the first dimension. Next we will take the rows of A and make them unroll into the columns, and finally the columns of A and make them go over each plane.
The result is that each column will be a unique RGB pixel that describes your image. How the unrolling will work though is that it will go in column-major order. We can then use linear indexing to split them up into arrays like so:
N = numel(A)/3;
V = B(1 : N);
W = B(N + 1 : 2*N);
X = B(2*N + 1 : end);
The job of linear indexing is that you access elements using a single index, rather than indexing each dimension separately. How linear indexing would work here is that if we had an image that was X x Y x 3, after permutation, the image would be reshaped such that it became a 3 x X x Y matrix. N in our case would be the total number of elements in a single plane. Because you are trying to split up the image into 3 vectors, the above operation where it's calculating N should be able to evenly divide by 3 as we have three colour planes to deal with.
By doing B(1 : N), we would access all of the elements from the first slice, second slice, in column-major format up until we retrieve N elements. These get placed into V. We then continue from this point and grab N more elements and place them into W, and finally the rest go into X.
If you want to access the pixels in row-major order, you simply need to change the way permute is accessing the dimensions like so:
B = permute(A, [3 2 1]);
You would then just access the elements with the above code normally. If you don't want to use linear indexing, you could use reshape to reshape the matrix such that it becomes a three-column matrix, where each column would be the desired vector:
C = reshape(B, [], 3);
V = C(:,1);
W = C(:,2);
X = C(:,3);
From your 4x4x3 example it's clear that you want to index first with the color index. I assume you then want row and then column. In that case, if A is your image (3D array), your desired three vectors are the columns of
B = reshape(permute(A,[3 1 2]),[],3);
So, if you need those vectors as explicit variables,
vector1 = B(:,1);
vector2 = B(:,2);
vector3 = B(:,3);
If the desired index order is color, then column, then row, use
B = reshape(permute(A,[3 2 1]),[],3);