Matlab finding three elements in the middle of a matrix - matlab

Lets say I have a matrix of x = [1;2;3;4;5;6;7;8;9;10;11]
I need to find the three middle numbers in that matrix (without counting or hard-coding) and assign it to a variable say y
So the y will be assigned the three middle elements in any data set.
How would I accomplish this?

To select the three entries in the middle of vector x, you can use
y = x(ceil(end/2)+[-1 0 1]);
More about this use of end can be found here.

Related

Minimum mean square in three dimension

I have two matrix, X and Y, both of them are of dimensions (4,24,16) correspondent to indices (i,j,z), I need to get the minimal mean square between then and it's index with reference to j. I means I will need to compare every vector and get the minimal difference in the vector j. I mean I should get the index between 1 and 24. here are example matrix,
clear all; clc; clear;
X = randn(4,24,16);
Y = randn(4,24,16);
but then I stuck how to do the minimum mean square with respect to second dimension j !
please any help ?
Execute mean on third and first dimension, thus resulting in second dimension that you can find the minimum value on:
MSE2=mean(mean( (X-Y).^2 ,3),1)
[mmse, argmmse]=min(MSE2);

Putting vectors of different size in a matrix

I am trying to add a number of vectors in a Matrix where each row represents a vector, but it gives me "Subscripted assignment dimension mismatch." error. The main problem is that each vector has a different size. I tried to add zeros at the end of the short vectors but I couldn't do it. Any Help.
Example:
%signal is a vector of data.
[x(1,:),y(1,:)] = findpeaks(signal1);
[x(2,:),y(2,:)] = findpeaks(signal2); %error as the peaks count in signal 2 is not the same as in signal 1.
OK, given two vectors of unequal length,
A=rand(1,10)
B=rand(1,5)
the proper way to deal with this is to use a cell array
D={A;B}
And then you can get whatever elements you want like this, for example:
D{1}(1:3) %// A(1:3)
If you don't want to use cells, you can add rows using this little function that adds row vector M to matrix F
addRow=#(F,M) [F NaN(size(F,1),size(M,2)-size(F,2));M NaN(1,size(F,2)-size(M,2))]
you would use it like this:
F=A
F=addRow(F,B)

Remove duplicates in correlations in matlab

Please see the following issue:
P=rand(4,4);
for i=1:size(P,2)
for j=1:size(P,2)
[r,p]=corr(P(:,i),P(:,j))
end
end
Clearly, the loop will cause the number of correlations to be doubled (i.e., corr(P(:,1),P(:,4)) and corr(P(:,4),P(:,1)). Does anyone have a suggestion on how to avoid this? Perhaps not using a loop?
Thanks!
I have four suggestions for you, depending on what exactly you are doing to compute your matrices. I'm assuming the example you gave is a simplified version of what needs to be done.
First Method - Adjusting the inner loop index
One thing you can do is change your j loop index so that it only goes from 1 up to i. This way, you get a lower triangular matrix and just concentrate on the values within the lower triangular half of your matrix. The upper half would essentially be all set to zero. In other words:
for i = 1 : size(P,2)
for j = 1 : i
%// Your code here
end
end
Second Method - Leave it unchanged, but then use unique
You can go ahead and use the same matrix like you did before with the full two for loops, but you can then filter the duplicates by using unique. In other words, you can do this:
[Y,indices] = unique(P);
Y will give you a list of unique values within the matrix P and indices will give you the locations of where these occurred within P. Note that these are column major indices, and so if you wanted to find the row and column locations of where these locations occur, you can do:
[rows,cols] = ind2sub(size(P), indices);
Third Method - Use pdist and squareform
Since you're looking for a solution that requires no loops, take a look at the pdist function. Given a M x N matrix, pdist will find distances between each pair of rows in a matrix. squareform will then transform these distances into a matrix like what you have seen above. In other words, do this:
dists = pdist(P.', 'correlation');
distMatrix = squareform(dists);
Fourth Method - Use the corr method straight out of the box
You can just use corr in the following way:
[rho, pvals] = corr(P);
corr in this case will produce a m x m matrix that contains the correlation coefficient between each pair of columns an n x m matrix stored in P.
Hopefully one of these will work!
this works ?
for i=1:size(P,2)
for j=1:i
Since you are just correlating each column with the other, then why not just use (straight from the documentation)
[Rho,Pval] = corr(P);
I don't have the Statistics Toolbox, but according to http://www.mathworks.com/help/stats/corr.html,
corr(X) returns a p-by-p matrix containing the pairwise linear correlation coefficient between each pair of columns in the n-by-p matrix X.

Matlab: Placing Zeros In A Three Dimensional Matrix

I am using a for loop to calculate the electric potential on a subset of the xy-plane (a square grid). Here is the code:
L=2;
for i=1:L
for j=1:L
for k=1:L
V(i,j,k)= -10;
end
end
end
where L is the length of the subset of the xy-plane. The difficulty I am having, however, is that I want the z component of the electric potential to be zero, I just want to the region in the xy-plane to be nonzero. The reason why I am using three dimensions is because I am going to eventually introduce an object, which is at a different electric potential relative to the plane, that is above the plane.
What I tried was taking a simple two dimensional matrix:
a =
1 1 1
1 1 1
and tried replacing the ones in the second column with zeros, which I did by typing a(:,2)=0, and matlab gave me
a =
1 0 1
1 0 1
I then tried to generalize this to a 3 dimensional matrix, but ran into some difficulty. Could someone help me?
I assume you want to set the 2nd component of a 3 dimensional matrix to zero.
You can do this in the same way as you do for 2 dimensional case.
A = ones(3,3,3) % Never use For Loops the way you did for operating on matrices.
A(:,2,:) = 0
%allocate the matrix:
V=nan(L,L,L)
%fill z=0 with intended potential. Assign a scalar to have identical
%values or a matrix to set individually
V(:,:,1)=-10
%set all other numbers to zero:
V(:,:,2:end)=0
You could merge the first and third step by allocating with zeros(L,L,L), but I think this way it's more obvious.

Need some help understanding the MATLAB `cat` command in high dimensions

The commands
a = magic(3);
b = pascal(3);
c = cat(4,a,b);
produce a 3-by-3-by-1-by-2 array.
Why is the result 3-3-1-2 when the dimension is 4?
Both a and b are two-dimensional matrices of size 3-by-3. When you concatenate them along a fourth dimension, the intervening third dimension is singleton (i.e. 1). So c(:,:,1,1) will be your matrix a and c(:,:,1,2) will be your matrix b.
Here's a link to some documentation that may help with understanding multidimensional arrays.
EDIT:
Perhaps it will help to think of these four dimensions in terms that us humans can more easily relate to...
Let's assume that the four dimensions in the example represent three dimensions in space (x, y, and z) plus a fourth dimension time. Imagine that I'm sampling the temperature in the air at a number of points in space at one given time. I can sample the air temperature in a grid that comprises all combinations of three x positions, three y positions, and one z position. That will give me a 3-by-3-by-1 grid. Normally, we'd probably just say that the data is in a 3-by-3 grid, ignoring the trailing singleton dimension.
However, let's say that I now take another set of samples at these points at a later time. I therefore get another 3-by-3-by-1 grid at a second time point. If I concatenate these sets of data together along the time dimension I get a 3-by-3-by-1-by-2 matrix. The third dimension is singleton because I only sampled at one z value.
So, in the example c=cat(4,a,b), we are concatenating two matrices along the fourth dimension. The two matrices are 3-by-3, with the third dimension implicitly assumed to be singleton. However, when concatenating along the fourth dimension we end up having to explicitly show that the third dimension is still there by listing its size as 1.