how to plot each profile with a distance from the other in a 2D plot? - matlab

I want to plot something like this http://www.nature.com/nprot/journal/v9/n6/fig_tab/nprot.2014.090_F7.html or like this one http://file.scirp.org/Html/11-2200285/ff6819f9-5db9-4121-852d-a8d5c302a5a4.jpg I have a 2D matrix.
I tried to plot it like this but did not work
figure;
hold on
for i = 1:size(X,1)
plot(X(i,:)+10)
end

Since you do not specify what exactly does not work, I am having some difficulties to answer your question directly (I do not have enough reputation for a comment).
The following code results in an image like the ones you link. Maybe you forgot to multiply the y-shift with the iteration number i.
N = 200;
x = 1:N;
M = 5;
X = sin(kron(x,ones(M,1)));
figure; hold all;
for i=1:N
plot(X(i,:)+i*5);
end

Related

Generate trajectories for 3 agents/robots with same tangent in specific point - MATLAB

I want to simulate the movements of 3 robots/agents in space and I would like to generate 3 different trajectories which have one constraint: in a certain time T the all the trajectories must have the same tangent.
I want something like in the following picture:
I need to do it through MATLAB and/or SIMULINK.
Thanks a lot for your help.
I do not know if this is enough for what I need or not but I probably figured out something.
What I did is to fit a polynomial to some points and constraining the derivative of the polynomial in a certain point to be equal to 0.
I used the following function:
http://www.mathworks.com/matlabcentral/fileexchange/54207-polyfix-x-y-n-xfix-yfix-xder-dydx-
It is pretty easy, but it saved me some work.
And, if you try the following:
% point you want your functions to pass
p1 = [1 1];
p2 = [1 3];
% First function
x1 = linspace(0,4);
y1 = linspace(0,4);
p = polyfix(x1,y1,degreePoly,p1(1),p1(2),[1],[0]);
% p = [-0.0767 0.8290 -1.4277 1.6755];
figure
plot(x1,polyval(p,x1))
xlim([0 3])
ylim([0 3])
grid on
hold on
% Second function
x2 = linspace(0,4);
y2 = linspace(0,4);
p = polyfix(x2,y2,degreePoly,[1],[3],[1],[0])
% p = [0.4984 -2.7132 3.9312 1.2836];
plot(x2,polyval(p,x2))
xlim([0 3])
ylim([0 3])
grid on
If you don't have the polyfix function and you don't want to download it you can try the same code commenting the polyfix lines:
p = polyfix(x1,y1,degreePoly,p1(1),p1(2),[1],[0]);
p = polyfix(x2,y2,degreePoly,p2(1),p2(1),[1],[0]);
And uncommenting the lines:
% p = [-0.0767 0.8290 -1.4277 1.6755];
% p = [0.4984 -2.7132 3.9312 1.2836];
You will get this:
Now I will use this polynomial as a position (x,y) over time of my robots and I think I should be done. The x of the polynomial will be also the time, in this way I am sure that the robots will arrive in the 0-derivative point at the same time.
What do you think? Does it make sense?
Thanks again.
To have tangents same all the time, curves (or trajectories) needs to be always parallel. Generate trajectory for one object and keep other objects at fixed distance apart and following master trajectory.
In image provides if we take time next to three dots trajectories will not be same (or parallel) as objects moved in different directions. So i guess you've to keep then always parallel

matlab plotting a family of functions

Generate a plot showing the graphs of
y=(2*a+1)*exp(-x)-(a+1)*exp(2*x)
in the range x ∈ <-2, 4> for all integer values of a between -3 and 3
I know how to make typical plot for 2 values and set a range on the axes, but how to draw the graph dependent on the parameter a?
To elaborate on Ben Voigt's comment: A more advanced technique would be to replace the for-loop with a call to bsxfun to generate a matrix of evaluations of M(i,j) = f(x(i),a(j)) and call plot with this matrix. Matlab will then use the columns of the matrix and plot each column with individual colors.
%%// Create a function handle of your function
f = #(x,a) (2*a+1)*exp(-x)-(a+1)*exp(2*x);
%%// Plot the data
x = linspace(-2, 4);
as = -3:3;
plot(x, bsxfun(f,x(:),as));
%%// Add a legend
legendTexts = arrayfun(#(a) sprintf('a == %d', a), as, 'uni', 0);
legend(legendTexts, 'Location', 'best');
You could also create the evaluation matrix using ndgrid, which explicitly returns all combinations of the values of x and as. Here you have to pay closer attention on properly vectorizing the code. (We were lucky that the bsxfun approach worked without having to change the original f.)
f = #(x,a) (2*a+1).*exp(-x)-(a+1).*exp(2*x); %// Note the added dots.
[X,As] = ndgrid(x,as);
plot(x, f(X,As))
However for starters, you should get familiar with loops.
You can do it using a simple for loop as follows. You basically loop through each value of a and plot the corresponding y function.
clear
clc
close all
x = -2:4;
%// Define a
a = -3:3;
%// Counter for legend
p = 1;
LegendText = cell(1,numel(a));
figure;
hold on %// Important to keep all the lines on the same plot.
for k = a
CurrColor = rand(1,3);
y= (2*k+1).*exp(-x)-(k+1).*exp(2.*x);
plot(x,y,'Color',CurrColor);
%// Text for legend
LegendText{p} = sprintf('a equals %d',k);
p = p+1;
end
legend(LegendText,'Location','best')
Which gives something like this:
You can customize the graph as you like. Hope that helps get you started!

Sequential connecting points in 2D in Matlab

I was wondering if you could advise me how I can connect several points together exactly one after each other.
Assume:
data =
x y
------------------
591.2990 532.5188
597.8405 558.6672
600.0210 542.3244
606.5624 566.2938
612.0136 546.6825
616.3746 570.6519
617.4648 580.4575
619.6453 600.0688
629.4575 557.5777
630.5477 584.8156
630.5477 618.5906
639.2696 604.4269
643.6306 638.2019
646.9013 620.7697
652.3525 601.1584
"data" is coordinate of points.
Now, I would like to connect(plot) first point(1st array) to second point, second point to third point and so on.
Please mind that plot(data(:,1),data(:,2)) will give me the same result. However, I am looking for a loop which connect (plot) each pair of point per each loop.
For example:
data1=data;
figure
scatter(X,Y,'.')
hold on
for i=1:size(data,1)
[Liaa,Locbb] = ismember(data(i,:),data1,'rows');
data1(Locbb,:)=[];
[n,d] = knnsearch(data1,data(i,:),'k',1);
x=[data(i,1) data1(n,1)];
y=[data(i,2) data1(n,2)];
plot(x,y);
end
hold off
Although, the proposed loop looks fine, I want a kind of plot which each point connect to maximum 2 other points (as I said like plot(x,y))
Any help would be greatly appreciated!
Thanks for all of your helps, finally a solution is found:
n=1;
pt1=[data(n,1), data(n,2)];
figure
scatter(data(:,1),data(:,2))
hold on
for i=1:size(data,1)
if isempty(pt1)~=1
[Liaa,Locbb] = ismember(pt1(:)',data,'rows');
if Locbb~=0
data(Locbb,:)=[];
[n,d] = knnsearch(data,pt1(:)','k',1);
x=[pt1(1,1) data(n,1)];
y=[pt1(1,2) data(n,2)];
pt1=[data(n,1), data(n,2)];
plot(x,y);
end
end
end
hold off
BTW it is possible to delete the last longest line as it is not related to the question, if someone need it please let me know.
You don't need to use a loop at all. You can use interp1. Specify your x and y data points as control points. After, you can specify a finer set of points from the first x value to the last x value. You can specify a linear spline as this is what you want to accomplish if the behaviour you want is the same as plot. Assuming that data is a 2D matrix as you have shown above, without further ado:
%// Get the minimum and maximum x-values
xMin = min(data(:,1));
xMax = max(data(:,1));
N = 3000; % // Specify total number of points
%// Create an array of N points that linearly span from xMin to xMax
%// Make N larger for finer resolution
xPoints = linspace(xMin, xMax, N);
%//Use the data matrix as control points, then xPoints are the values
%//along the x-axis that will help us draw our lines. yPoints will be
%//the output on the y-axis
yPoints = interp1(data(:,1), data(:,2), xPoints, 'linear');
%// Plot the control points as well as the interpolated points
plot(data(:,1), data(:,2), 'rx', 'MarkerSize', 12);
hold on;
plot(xPoints, yPoints, 'b.');
Warning: You have two x values that map to 630.5477 but produce different y values. If you use interp1, this will give you an error, which is why I had to slightly perturb one of the values by a small amount to get this to work. This should hopefully not be the case when you start using your own data. This is the plot I get:
You'll see that there is a huge gap between those two points I talked about. This is the only limitation to interp1 as it assumes that the x values are strictly monotonically increasing. As such, you can't have the same two points in your set of x values.

How to do an animated plot in matlab

I was wondering if anyone knew how to do an animation plot of
x = (dataset of 1000 points)
y = (dataset of 1000 points)
plot(x,y)
big problem is these are datasets that i am trying to plot , or x,y coordinates as opposed to a function which I would know how to plot via an animation.
I tried to do frames in a for loop but it gave me dots and didn't join them in a line graph so I couldn't really watch the path being traced out.
code I used was
for i = 1:length(DATASET1)
pause(0.1)
plot(DATASET1(i),DATASET2(i))
draw on
end
If what you want is for the plot to "grow" point by point: the easiest way is to create an empty plot and then update its XData and YData properties at each iteration:
h = plot(NaN,NaN); %// initiallize plot. Get a handle to graphic object
axis([min(DATASET1) max(DATASET1) min(DATASET2) max(DATASET2)]); %// freeze axes
%// to their final size, to prevent Matlab from rescaling them dynamically
for ii = 1:length(DATASET1)
pause(0.01)
set(h, 'XData', DATASET1(1:ii), 'YData', DATASET2(1:ii));
drawnow %// you can probably remove this line, as pause already calls drawnow
end
Here's an example1 obtained with DATASET1 = 1:100; DATASET2 = sin((1:100)/6);
1 In case someone's interested, the figure is an animated gif which can be created by adding the following code (taken from here) within the loop, after the drawnow line:
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if ii == 1;
imwrite(imind,cm,filename,'gif','Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
Looks like you were close. Not sure draw on is any command though.
See if the code here inspires you to solve your case -
%// Sample x and y values assumed for demo.
x = 1:1000;
y = x.^2;
%// Plot starts here
figure,hold on
%// Set x and y limits of the plot
xlim([min(x(:)) max(x(:))])
ylim([min(y(:)) max(y(:))])
%// Plot point by point
for k = 1:numel(x)
plot(x(k),y(k),'-') %// Choose your own marker here
%// MATLAB pauses for 0.001 sec before moving on to execue the next
%%// instruction and thus creating animation effect
pause(0.001);
end
Since R2014b, you can work with annimatedline object (doc and how-to) that is meant to handle animated graphs pretty well. Basically, the annimatedline object has a addpoints function that adds new points to the line without having to redefine the existing points, along with a clearpoints function that clears lines for more complex animations.
Here is an example:
h = animatedline;
axis([0,4*pi,-1,1])
x = linspace(0,4*pi,1000);
y = sin(x);
for k = 1:length(x)
addpoints(h,x(k),y(k));
drawnow
end

How to overlay histograms in matlab

I have multiple histograms that I would like to overlay on top of each other but I don't know how to do it. I found the code below but I don't know how to modify it to run on a loop instead of just two histograms.
data1 = randn(100,1); % data of one size
data2 = randn(25, 1); % data of another size!
myBins = linspace(-3,3,10); % pick my own bin locations
% Hists will be the same size because we set the bin locations:
y1 = hist(data1, myBins);
y2 = hist(data2, myBins);
% plot the results:
figure(3);
bar(myBins, [y1;y2]');
title('Mixed size result');
or what is a better way of comparing histograms if they are more than 10 or 20.
Your question is very general. Firstly I do not understand why you insist on a for loop.
Personally I don't like the included bar plot. It quickly gets messy (especially since the bars are not at the "original" location)
If you got a lot of histograms I would consider a stairstep plot as it doesn't fill the plot area so much. Or you could come up with your own - eg using transparent patches.
If it get's lots of curves there are many ways to visualize them google for "multivariate visualization" and be amazed. One of the most amusing ways would be Chernoff faces.
it's much easier now:
histogram(data1, myBins);
hold on;
histogram(data2, myBins);
You could do the following, although it's not the only way:
data = cell(1, N);
y = cell(1, N);
yBar = zeros(N, 10);
for i=1:N
data{1, i} = randn(10*round(rand(1,1)), 1);
y{1, i} = hist(data{1, i}, myBins);
yBar(i, :) = y{1, i};
end
yBar = yBar';
figure(3);
bar(myBins, yBar);
title('Mixed size result');
Using the y cell is not obligatory of course, I left it there to actually show what's happening.
I would suggest this. It's simple and does not require for loops:
bar([y1.' y2.'],'stacked')
Here's a way that was useful to me:
I'm plotting a histogram for each column of the matrix ao.
The code was:
for i = 1:size(ao,2)
[h, y] = hist(ao(:,i), linspace(-5,10,100));
h = i + (0.95./max(h(:))) .* h;
barh(y, h, 'BarWidth', 1, 'BaseValue', i, 'LineStyle', 'none');
hold on;
end
grid;
Note that just changing barh to bar will give the same thing but going up-down instead of left-right (i.e. the figure rotated by 90° anti-clockwise).