Calculate mean of columns only - matlab

I have a function that calculates the mean of two columns of a matrix. For example, if the following matrix is the input:
inputMatrix =
1 2 5 3 9
4 6 2 3 2
4 4 3 9 1
... And my command is:
outputVector = mean(inputArray(:,1:2))
...Then my output is:
outputVector =
3 4
The problem arises when my input matrix only contains one row (i.e. when it is a vector, not a matrix).
For example, the input:
inputMatrix =
4 3 7 2 1
Gives the output:
outputVector =
3.5000
I would like the same behaviour to be maintained regardless of how many rows are in the input. To clarify, the correct output for the second example above should be:
outputVector =
4 3

Use the second argument of MEAN to indicate along which dimension you want to average
inputMatrix =[ 4 3 7 2 1]
mean(inputMatrix(:,1:2),1) %# average along dim 1, i.e. average all rows
ans =
4 3

mean(blah, 1)
See the documentation: http://www.mathworks.co.uk/help/techdoc/ref/mean.html.

Related

Reshape a matrix by splitting it after k columns in MATLAB

Suppose that I have a matrix , let's call it A, as follows:
1 2 3 4 5 1 2 3 4 5
0 2 4 6 8 1 3 5 7 9
And I want to reshape it into a matrix like this:
1 2 3 4 5
0 2 4 6 8
1 2 3 4 5
1 3 5 7 9
So, basically, what I want to be done is that MATLAB first reads a block of size (2,5) and then splits the remaining matrix to the next row and then repeats this so on so forth until we get something like in my example.
I tried to do this using MATLAB's reshape command in several ways but I failed. Any help is appreciated. In case that it matters, my original data is larger. It's (2,1080). Thanks.
I don't believe you can do this in a single command, but perhaps someone will correct me. If speed isn't a huge concern a for loop should work fine.
Alternatively you can get your results by reshaping each row of A and then placing the results into every other row of a new matrix. This will also work with your larger data.
A = [1 2 3 4 5 1 2 3 4 5
0 2 4 6 8 1 3 5 7 9];
An = zeros(numel(A)/5, 5); % Set up new, empty matrix
An(1:2:end,:) = reshape(A(1,:), 5, [])'; % Write the first row of A to every other row of An
An(2:2:end,:) = reshape(A(2,:), 5, [])' % Write second row of A to remaining rows
An =
1 2 3 4 5
0 2 4 6 8
1 2 3 4 5
1 3 5 7 9
You may need to read more about indexing in the Matlab's documentation.
For your example, it is easy to do the following
A=[1 2 3 4 5 1 2 3 4 5; 0 2 4 6 8 1 3 5 7 9]
a1=A(:,1:5); % extract all rows, and columns from 1 to 5
a2=A(:,6:end); % extract all rows, and columns from 6 to end
B=[a1;a2] % construct a new matrix.
It is not difficult to build some sort of loops to extract the rest.
Here's a way you can do it in one line using the reshape and permute commands:
B = reshape(permute(reshape(A,2,5,[]), [1,3,2]), [], 5);
The reshape(A,2,5,[]) command reshapes your A matrix into a three-dimensional tensor of dimension 2 x 5 x nblocks, where nblocks is the number of blocks in A in the horizontal direction. The permute command then swaps the 2nd and 3rd dimensions of this 3D tensor, so that it becomes a 2 x nblocks x 5 tensor. The final reshape command then transforms the 3D tensor into a matrix of dimension (2*nblocks) x 5.
Looking at the results at each stage may give you a better idea of what's happening.

Indices of max values in matrix

Let's say I have the following matrix:
j =
1 2 3 4
1 2 3 4
5 6 7 8
5 6 7 8
I would like to get back the following matrix:
z =
3 4
4 4
My experience with the max command hasn't yielded a result that resembles z, it appears that the max function turns the argument into a column vector.
It appears you want the row and column indices of all occurrences of the maximum computed across all dimensions (i.e. the maximum is a single value, which possibly appears in several entries). Then:
[rows, cols] = find(j==max(j(:)));
result = [rows cols];

dot product of matrix columns

I have a 4x8 matrix which I want to select two different columns of it then derive dot product of them and then divide to norm values of that selected columns, and then repeat this for all possible two different columns and save the vectors in a new matrix. can anyone provide me a matlab code for this purpose?
The code which I supposed to give me the output is:
A=[1 2 3 4 5 6 7 8;1 2 3 4 5 6 7 8;1 2 3 4 5 6 7 8;1 2 3 4 5 6 7 8;];
for i=1:8
for j=1:7
B(:,i)=(A(:,i).*A(:,j+1))/(norm(A(:,i))*norm(A(:,j+1)));
end
end
I would approach this a different way. First, create two matrices where the corresponding columns of each one correspond to a unique pair of columns from your matrix.
Easiest way I can think of is to create all possible combinations of pairs, and eliminate the duplicates. You can do this by creating a meshgrid of values where the outputs X and Y give you a pairing of each pair of vectors and only selecting out the lower triangular part of each matrix offsetting by 1 to get the main diagonal just one below the diagonal.... so do this:
num_columns = size(A,2);
[X,Y] = meshgrid(1:num_columns);
X = X(tril(ones(num_columns),-1)==1); Y = Y(tril(ones(num_columns),-1)==1);
In your case, here's what the grid of coordinates looks like:
>> [X,Y] = meshgrid(1:num_columns)
X =
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
Y =
1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
As you can see, if we select out the lower triangular part of each matrix excluding the diagonal, you will get all combinations of pairs that are unique, which is what I did in the last parts of the code. Selecting the lower-part is important because by doing this, MATLAB selects out values column-wise, and traversing the columns of the lower-triangular part of each matrix gives you the exact orderings of each pair of columns in the right order (i.e. 1-2, 1-3, ..., 1-7, 2-3, 2-4, ..., etc.)
The point of all of this is that can then use X and Y to create two new matrices that contain the columns located at each pair of X and Y, then use dot to apply the dot product to each matrix column-wise. We also need to divide the dot product by the multiplication of the magnitudes of the two vectors respectively. You can't use MATLAB's built-in function norm for this because it will compute the matrix norm for matrices. As such, you have to sum over all of the rows for each column respectively for each of the two matrices then multiply both of the results element-wise then take the square root - this is the last step of the process:
matrix1 = A(:,X);
matrix2 = A(:,Y);
B = dot(matrix1, matrix2, 1) ./ sqrt(sum(matrix1.^2,1).*sum(matrix2.^2,1));
I get this for B:
>> B
B =
Columns 1 through 11
1 1 1 1 1 1 1 1 1 1 1
Columns 12 through 22
1 1 1 1 1 1 1 1 1 1 1
Columns 23 through 28
1 1 1 1 1 1
Well.. this isn't useful at all. Why is that? What you are actually doing is finding the cosine angle between two vectors, and since each vector is a scalar multiple of another, the angle that separates each vector is in fact 0, and the cosine of 0 is 1.
You should try this with different values of A so you can see for yourself that it works.
To make this code compatible for copying and pasting, here it is:
%// Define A here:
A = repmat(1:8, 4, 1);
%// Code to produce dot products here
num_columns = size(A,2);
[X,Y] = meshgrid(1:num_columns);
X = X(tril(ones(num_columns),-1)==1); Y = Y(tril(ones(num_columns),-1)==1);
matrix1 = A(:,X);
matrix2 = A(:,Y);
B = dot(matrix1, matrix2, 1) ./ sqrt(sum(matrix1.^2,1).*sum(matrix2.^2,1));
Minor Note
If you have a lot of columns in A, this may be very memory intensive. You can get your original code to work with loops, but you need to change what you're doing at each column.
You can do something like this:
num_columns = nchoosek(size(A,2),2);
B = zeros(1, num_columns);
counter = 1;
for ii = 1 : size(A,2)
for jj = ii+1 : size(A,2)
B(counter) = dot(A(:,ii), A(:,jj), 1) / (norm(A(:,ii))*norm(A(:,jj)));
counter = counter + 1;
end
end
Note that we can use norm because we're specifying vectors for each of the inputs into the function. We first preallocate a matrix B that will contain the dot products of all possible combinations. Then, we go through each pair of combinations - take note that the inner for loop starts from the outer most for loop index added with 1 so you don't look at any duplicates. We take the dot product of the corresponding columns referenced by positions ii and jj and store the results in B. I need an external counter so we can properly access the right slot to place our result in for each pair of columns.

Sample from matrix and record matrix index in Matlab

I have a two column matrix of the following form:
1. 1 1
2. 1 1
3. 1 2
4. 1 2
5. 2 2
6. 2 2
7. 3 2
8. 3 2
9. 3 3
10. 4 3
11. 4 4
I would like to sample a single number from the first column using say randsample().
Let's say the results is 2.
What I would like to know is which ROW was the sample taken from? (in this case it could have been sampled both from row 5 or row 6)
Is this possible?
It's easy with find and ==:
>> A = [
1 1
1 1
1 2
1 2
2 2
2 2
3 2
3 2
3 3
4 3
4 4];
>> R = randsample(4,1)
>> find(A(:,1) == R)
R =
4
ans =
10
11
Or, as indicated by igor milla,
>> I = randi(11)
>> A(I, :)
I =
9
ans =
3 3
If you just need to sample one value, the solution as given by #igor milla is fine. But if you want to use the options given by randsample then I would recommend you to sample the column numbers rather than the sample directly.
A = rand(11,2); %suppose this is your matrix
k = 1; %This is the size of your desired sample
mysampleid = randsample(size(A,1),k)
mysample = A(mysampleid,:)
Now mysampleid contains the numbers of the columns, and mysample contains the rows that you sampled.
If you just want to sample the first column you can use A(mysampleid,1) instead.

Sorting entire matrix according to one column in matlab

I have the matrix as follows
a =
1 3
2 5
3 2
4 8
5 9
I want to sort the second column in the a matrix. I want the corresponding rows of column one to be printed as follows :
a =
3 2
1 3
2 5
4 8
5 9
I tried sort(a), but it is sorting only the second column of matrix a.
Try this:
sortrows(a,2)
This should sort according to the second column.
or use:
[val idx]=sort(a(:,2));
ans = [a(idx,1) val]