Interpolation with MATLAB in EMG processing - matlab

I have 3 EMG recordings for 2 muscles, with a sampling rate of 1000Hz. In other words I have 3 matrices of EMG data; each has 2 rows (for 2 muscles).
However the number of samples (columns) in each isn't the same: the first one has 2600 samples, the second has 2500 samples and the third one has 2550 samples.
I want to make their lengths the same as each other, to get 3 matrices with the same number of rows and columns. I think it is foolish to cut the bigger ones and use just 2500 columns. However if I want to do so, I don't know whether I should cut from the start or end of them?
Is there a way in MATLAB to interpolate the data to get 3 matrices, each of size 3 x 2600?
All 3 matrices belong to the same movement, and I want to match the samples.

You most likely want to look at using interp1 in this situation. This performs an interpolation between your points so that you can sample at any position on the x-axis.
http://www.mathworks.com/help/matlab/ref/interp1.html
I have the following example which has some random sample data sample1, sample2 and sample3. These variables are of lengths 2600, 2500 and 2550 respectively.
sample1 = exp(2*linspace(0,1,2600)+rand(1, 2600));
sample2 = exp(linspace(0,1,2500)+rand(1, 2500));
sample3 = exp(3*linspace(0,1,2550)+rand(1, 2550));
I have a desired length (I am using a length which corresponds to your shortest sample size)
desiredlength = 2500;
You can then interpolate your data with the following code (note the default is a linear interpolation):
adjusted = zeros(3, desiredlength);
adjusted(1, :) = interp1(linspace(0,1,length(sample1)), sample1, linspace(0,1,desiredlength));
adjusted(2, :) = interp1(linspace(0,1,length(sample2)), sample2, linspace(0,1,desiredlength));
adjusted(3, :) = interp1(linspace(0,1,length(sample3)), sample3, linspace(0,1,desiredlength));
plot(adjusted')
linspace(a, b, n) is a function which gives you a vector of n points between a and b, and for sample1 I am transforming from linspace(0, 1, 2600) to linspace(0, 1, 2500)
I hope this helps.

Related

How do I visualize n-dimensional features?

I have two matrices A and B. The size of A is 200*1000 double (here: 1000 represents 1000 different features). Matrix A belongs to group 1, where I use ones(200,1) as the label vector. The size of B is also 200*1000 double (here: 1000 also represents 1000 different features). Matrix B belongs to group 2, where I use -1*ones(200,1) as the label vector.
My question is how do I visualize matrices A and B so that I can clearly distinguish them based on the given groups?
I'm assuming each sample in your matrices A and B is determined by a row in either matrix. If I understand you correctly, you want to draw a series of 1000-dimensional vectors, which is impossible. We can't physically visualize anything beyond three dimensions.
As such, what I suggest you do is perform a dimensionality reduction to reduce your data so that each input is reduced to either 2 or 3 dimensions. Once you reduce your data, you can plot them normally and assign a different marker to each point, depending on what group they belonged to.
If you want to achieve this in MATLAB, use Principal Components Analysis, specifically the pca function in MATLAB, that calculates the residuals and the reprojected samples if you were to reproject them onto a lower dimensionality. I'm assuming you have the Statistics Toolbox... if you don't, then sorry this won't work.
Specifically, given your matrices A and B, you would do this:
[coeffA, scoreA] = pca(A);
[coeffB, scoreB] = pca(B);
numDimensions = 2;
scoreAred = scoreA(:,1:numDimensions);
scoreBred = scoreB(:,1:numDimensions);
The second output of pca gives you reprojected values and so you simply have to determine how many dimensions you want by extracting the first N columns, where N is the desired number of dimensions you want.
I chose 2 for now, and we can see what it looks like in 3 dimensions after. Once we have what we need for 2 dimensions, it's just a matter of plotting:
plot(scoreAred(:,1), scoreAred(:,2), 'rx', scoreBred(:,1), scoreBred(:,2), 'bo');
This will produce a plot where the samples from matrix A are with red crosses while the samples from matrix B are with blue circles.
Here's a sample run given completely random data:
rng(123); %// Set seed for reproducibility
A = rand(200,1000); B = rand(200,1000); %// Generate random data
%// Code as before
[coeffA, scoreA] = pca(A);
[coeffB, scoreB] = pca(B);
numDimensions = 2;
scoreAred = scoreA(:,1:numDimensions);
scoreBred = scoreB(:,1:numDimensions);
%// Plot the data
plot(scoreAred(:,1), scoreAred(:,2), 'rx', scoreBred(:,1), scoreBred(:,2), 'bo');
We get this:
If you want three dimensions, simply change numDimensions = 3, then change the plot code to use plot3:
plot3(scoreAred(:,1), scoreAred(:,2), scoreAred(:,3), 'rx', scoreBred(:,1), scoreBred(:,2), scoreBred(:,3), 'bo');
grid;
With those changes, this is what we get:

Making sense of CCA (Matlab implementation) 2

I am using CCA for my work and want to understand something.
This is my MATLAB code. I have only taken 100 samples to better understand the concepts of CCA.
clc;clear all;close all;
load carbig;
data = [Displacement Horsepower Weight Acceleration MPG];
data(isnan(data))=0;
X = data(1:100,1:3);
Y = data(1:100,4:5);
[wx,wy,~,U,V] = CCA(X,Y);
clear Acceleration Cylinders Displacement Horsepower MPG Mfg Model Model_Year Origin Weight when org
subplot(1,2,1),plot(U(:,1),V(:,1),'.');
subplot(1,2,2),plot(U(:,2),V(:,2),'.');
My plots are coming like this:
This points out that in the 1st figure (left), the transformed variables are highly correlated with little scatter around the central axis. While in the 2nd figure(right), the scatter around the central axis is much more.
As I understand from here that CCA maximizes the correlation between the data in the transformed space. So I tried to design a matching score which should return a minimum value if the vectors are maximally correlated. I tried to match each vector of U(i,:) with that of V(j,:) with i,j going from 1 to 100.
%% Finding the difference between the projected vectors
for i=1:size(U,1)
cost = repmat(U(i,:),size(U,1),1)- V;
for j=1:size(U,1)
c(i,j) = norm(cost(j,:),size(U,2));
end
[~,idx(i)] = min(c(i,:));
end
Ideally idx should be like this :
idx = 1 2 3 4 5 6 7 8 9 10 ....
as they are maximally correlated. However my output comes something like this :
idx = 80 5 3 1 4 7 17 17 17 10 68 78 78 75 9 10 5 1 6 17 .....
I dont understand why this happens.
Am I wrong somewhere ? Isnt the vectors supposed to be maximally correlated in the transformed CCA subspace?
If my above assumption is wrong, please point me out in the correct direction.
Thanks in advance.
First, Let me transpose your code in R2014b:
load carbig;
data = [Displacement Horsepower Weight Acceleration MPG];
% Truncate the data, to follow-up with your sample code
data = data(1:100,:);
nans = sum(isnan(data),2) > 0;
[wx, wy, r, U, V,] = canoncorr(X(~nans,1:3),X(~nans,4:5));
OK, now the trick is that the vectors which are maximally correlated in the CCA subspace are the column vectors U(:,1) with V(:,1) and U(:,2) with V(:,2), and not the row vectors U(i,:), as you are trying to compute. In the CCA subspace, vectors should be N-dimensional (here N=100), and not simple 2D vectors. That's the reason why visualization of CCA results is often quite complicated !
By the way, the correlations are given by the third output of canoncorr, that you (intentionally ?) choosed to skip in your code. If you check its content, you'll see that the correlations (i.e. the vectors) are well-ordered:
r =
0.9484 0.5991
It is hard to explain CCA better than the link you already provided. If you want to go further, you should probably invest in a book, like this one or this one.

Interpolation of time series data in MATLAB

I have a multidimensional time series in MATLAB. Let's say it's of M dimensions, N samples, and as such I have it stored in terms of NxM matrix.
I want interpolate the time series, to fit a new length (N1), where always N is always less than N1.
In other words, if I have multiple time series (all sampled at the same rate, just of different lengths), I want to interpolate them all to be of length N0.
How can one achieve this with MATLAB?
EDIT: Could one achieve this with imresize?
i.e.:
A = randn(5,10) % 10 dimensions, 5 samples
desiredLength = 15; % we want 15 samples in lenght
newA = imresize(A, [desiredLength 10], 'bilinear');
A procedure like the following might do what you want. The new data will be a linear interpolation of the old data.
[initSize1, initSize2] = ndgrid(1:size(Data, 1), 1:size(Data, 2));
[newSize1, newSize2] = ndgrid(linspace(1, size(Data, 1), newlength), 1:size(Data, 2));
newData = interpn(initSize1, initSize2, Data, newSize1, newSize2);
As coded up, only dimension 1 should change, as the second gridded dimension is the same in the first and second calls to ndgrid.
If you have a timeseries object, you might also want to look at the resample method for the timeseries object:
http://www.mathworks.co.uk/help/matlab/ref/timeseries.resample.html

plot two matrices both of (4*36 double) size in mat lab

I would like to plot two matrices both of (4*36 double) size. The first contains rho and the second contains depths for the 36 locations
well I looked into surf but it reads two arrays and one matrix rather than two matrices and yes I would like to plot them as column graph
here is an example
rho= magic(36);
rho(5:1:end,:)=[];
D= magic(36);
D(5:1:end,:)=[];
D=sort(depth);
So right now the matrix rho contains the densities for the 36 location at four different depths. The matrix D contains the four different depths at which the reading at rho is found. The first element in the first matrix corresponds to the first element in the second matrix and so on
in the end what I would like to have is the 36 column with the different reading from (rho) plotted against appropriate depth in (D)
I hope I helped make it clearer somehow
Simple example of plotting four sets of X and Y data:
X = repmat(1:36, [4 1]);
Y(1,:) = rand(1,36);
Y(2,:) = 0.2 * (1:36);
Y(3,:) = 5 * sin(linspace(-pi,pi,36));
Y(4,:) = 0.1 * (1:36).^2;
figure
plot(X', Y')
This results in
Note - in order to get four series to plot like this, the data has to be in COLUMNS. The original data was in 4x36 matrix, so it was in ROWS. I used the transpose operator (apostrophe - X' rather than just X) to get the data organized in columns.
Maybe this helps...

How to find Finite State-Transition probability matrix of Markov chain (FSMC)

I have channel measurements which has values > 20,000, which has to be divided into discrete levels, as in my case K=8 and which has to be mapped to channel measurements with states. I have to find state-transition probability matrix for this in Matlab.
My question is, I need to know how to divide these values into 8 states and to find the state-transition probability matrix for these 8 states in Matlab.
Here is a made-up example:
%# some random vector (load your data here instead)
x = randn(1000,1);
%# discretization/quantization into 8 levels
edges = linspace(min(x),max(x),8+1);
[counts,bins] = histc(x, edges);
%# fix last level of histc output
last = numel(counts);
bins(bins==last) = last - 1;
counts(last-1) = counts(last-1) + counts(last);
counts(last) = [];
%# show histogram
bar(edges(1:end-1), counts, 'histc')
%# transition matrix
trans = full(sparse(bins(1:end-1), bins(2:end), 1));
trans = bsxfun(#rdivide, trans, sum(trans,2));
A few things to note:
Discretization is performed simply by dividing the whole range of data into 8 bins. This is done using histc. Note that due to the way the function works, we had to combine the last two counts and fix the bins accordingly.
the transition matrix is computed by first counting the co-occurrences using a less-known call form of the sparse function. The accumarray could have also been used. The count matrix is then normalized to obtain probabilities that sum to one.
You mentioned that your MC model should only allow transitions between adjacent states (1 to 2 or 8 to 7, but not between 2 and 5). I did not enforce this fact since this should be a property of the data itself, which is not applicable in this example with random data.