Plotting rows of points in Matlab - matlab

So I'm still getting used to Matlab and am having a bit of trouble with plotting. I have a cell which contains a list of points in each row. I want to plot each row of points in a different colour on the same graph so I can compare them. The catch is that I need to make this work for an unknown number of points and rows (ie the number of points and rows can change each time I run the program).
So for example, I might have my cell array A:
A = {[0,0], [1,2], [3,4]; [0,0] [5,6], [9,2]}
and I want to plot the points in row 1 against their index (so a 3D graph) and then have the points in row 2 on the same graph in a different colour. The rows will always be the same length. (Each row will always have the same number of points). I've tried a few different for loops but just can't seem to get this right.
Any help in sending me in the right direction would be greatly appreciated!

The fact that the number of points and rows can change with each iteration should not pose much of a problem. I would suggest using the size function before your plot loops (size(A,1) and size(A,2)) to get the dimensions of the matrix.
Once you have the size of the matrix, loop through the dimensions and plot the lines on the same plot using holdon, and then finally just make the line color a function of the dimensions as you loop through so that you always have a different line color

You could just convert it to a matrix and plot it directly:
% Some dummy data - format a little different from your example
% to allow for different numbers of elements per row
A = {[0,0, 1,2, 3,4]; [0,0, 5,6]};
% Figure out how many columns we need in total
maxLen = max(cellfun(#length, A));
% Preallocate
Amat = NaN(size(A, 1), maxLen);
% Copy data
for n = 1:size(A, 1)
curA = A{n};
Amat(n, 1:length(curA)) = curA;
end
% Generate 1:N vector repeated the correct number of times (rows)
x = repmat(1:size(Amat, 2), size(Amat, 1), 1);
plot(x, Amat)
Edit: You mentioned a 3D graph at some point in your post. The above won't plot a 3D graph, so here's something that will:
% Generate Amat as above
% Then:
[X, Y] = meshgrid(1:size(Amat, 1), 1:size(Amat, 2));
surf(X, Y, Amat.'); % OR: plot3(X, Y, Amat.');
I'm not sure this is exactly what you want, but your question is slightly unclear on exactly what kind of graph you want out of this. If you just want coloured lines on your plot, you can use plot3 instead of surf, but IMHO surf will probably give you a clearer plot for this kind of data.

Related

Highlight specific section of graph in MATLAB

I wish to highlight/mark some parts of a array via plot in MATLAB. After some research (like here) I tried to hold the first plot, find the indexes for highlighting and then a new plot, only with those points. However, those points are being drawn but all shifted to the beginning of the axis:
I'm currently trying using this code:
load consumer; % the main array to plot (157628x10 double) - data on column 9
load errors; % a array containing the error indexes (1x5590 double)
x = 1:size(consumer,1)'; % returns a (157628x1 double)
idx = (ismember(x,errors)); % returns a (157628x1 logical)
fig = plot(consumer(:,9));
hold on, plot(consumer(idx,9),'r.');
hold off
Another thing I would like to do was highlighting the whole section of the graph, like a "patch" on the same sections. Any ideas?
The trouble is that you are only providing the y-axis data to the plot function. By default, this means all data is plotted on the 1:numel(y) x locations of your plot, where y is your y-axis data.
You have 2 options...
Also provide x-axis data. You've already got the array x anyway!
figure; hold on;
plot(x, consumer(:,9));
plot(x(idx), consumer(idx,9), 'r.');
Aside: I'm slightly confused why you create idx. If errors is as you describe it (indexes of the array) then you should just be able to use consumer(errors,9).
Make all data which you don't want to appear equal to NaN. Because of the way you're loading your error indices in, this is less quick and easy. Basically you'd copy consumer(:,9) into a new variable, and index all undesirable points to set them equal to NaN.
This method has the benefit of breaking up discontinuous sections too.
y = consumer(:,9); % copy your y data before changes
idx = ~ismember(x, errors); % get the indices you *don't* want to re-plot
y(idx) = NaN; % Set equal to NaN so they aren't plotted
figure; hold on;
plot(x, consumer(:,9));
plot(x, y, 'r'); % Plot all points, NaNs wont show

Indexing sections to plot in a MATLAB for loop

I have a matlab indexing question. I have a vector of 34 elements that I would like to plot in a for loop. However, I do not wish to plot them all at once. It would be great if I were able to plot elements 1:6, then 7:11, then 12:20, and so on. Is it possible to do this type of plotting in a for loop? If it is, I am having trouble with the indexing. Since these elements are all in sequential order, matlab seems to want to plot them all together. Any help would be appreciated. Thanks!
Here is an example of what I am trying to do:
for i = 1: [1:6, 7:11, 12:20]
plot(x(i), y(i))
end
Hopefully, I can get three plot, one with data from elements 1:6, another from elements 7:11, and the last one from elements 12:20.
You can just use a cell to store the variable-length vectors containing the various indices:
x = linspace(0, 1, 20);
y = x;
i_cell = {1:6, 7:11, 12:20};
for i = 1:length(i_cell)
figure
indices = i_cell{i}
plot(x(indices), y(indices))
end

Plot a cell into a time-changing curve

I have got a cell, which is like this : Data={[2,3],[5,6],[1,4],[6,7]...}
The number in every square brackets represent x and y of a point respectively. There will be a new coordinate into the cell in every loop of my algorithm.
I want to plot these points into a time-changing curve, which will tell me the trajectory of the point.
As a beginner of MATLAB, I have no idea of this stage. Thanks for your help.
Here is some sample code to get you started. It uses some basic Matlab functionalities that you will hopefully find useful as you continue using it. I added come data points to you cell array for illustrative purposes.
The syntax to access elements into the cell array might seem weird but is important. Look here for details about cell array indexing.
In order to give nice colors to the points, I generated an array based on the jet colormap built-in in Matlab. Basically issuing the command
Colors = jet(N)
create a N x 3 matrix in which every row is a 3-element color ranging from blue to red. That way you can see which points were detected before other (i.e. blue before red). Of course you can change that to anything you want (look here if you're interested).
So here is the code. If something is unclear please ask for clarifications.
clear
clc
%// Get data
Data = {[2,3],[5,6],[1,4],[6,7],[8,1],[5,2],[7,7]};
%// Set up a matrix to color the points. Here I used a jet colormap
%// available from MATLAB but that could be anything.
Colors = jet(numel(Data));
figure;
%// Use "hold all" to prevent the content of the figure to be overwritten
%// at every iterations.
hold all
for k = 1:numel(Data)
%// Note the syntax used to access the content of the cell array.
scatter(Data{k}(1),Data{k}(2),60,Colors(k,:),'filled');
%// Trace a line to link consecutive points
if k > 1
line([Data{k-1}(1) Data{k}(1)],[Data{k-1}(2) Data{k}(2)],'LineStyle','--','Color','k');
end
end
%// Set up axis limits
axis([0 10 0 11])
%// Add labels to axis and add a title.
xlabel('X coordinates','FontSize',16)
ylabel('Y coordinates','FontSize',16)
title('This is a very boring title','FontSize',18)
Which outputs the following:
This would be easier to achieve if all of your data was stored in a n by 2 (or 2 by n) matrix. In this case, each row would be a new entry. For example:
Data=[2,3;
5,6;
1,4;
6,7];
plot(Data(:, 1), Data(:, 2))
Would plot your points. Fortunately, Matlab is able to handle matrices which grow on every iteration, though it is not recommended.
If you really wanted to work with cells, there are a couple of ways you could do it. Firstly, you could assign the elements to a matrix and repeat the above method:
NumPoints = numel(Data);
DataMat = zeros(NumPoints, 2);
for I = 1:NumPoints % Data is a cell here
DataMat(I, :) = cell2mat(Data(I));
end
You could alternatively plot the elements straight from the cell, though this would limit your plot options.
NumPoints = numel(Data);
hold on
for I = 1:NumPoints
point = cell2mat(Data(I));
plot(point(1), point(2))
end
hold off
With regards to your time changing curve, if you find that Matlab starts to slow down after it stores lots of points, it is possible to limit your viewing window in time with clever indexing. For example:
index = 1;
SamplingRate = 10; % How many times per second are we taking a sample (Hertz)?
WindowTime = 10; % How far into the past do we want to store points (seconds)?
NumPoints = SamplingRate * WindowTime
Data = zeros(NumPoints, 2);
while running
% Your code goes here
Data(index, :) = NewData;
index = index + 1;
index = mod(index-1, NumPoints)+1;
plot(Data(:, 1), Data(:, 2))
drawnow
end
Will store your data in a Matrix of fixed size, meaning Matlab won't slow down.

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.

Matlab Boxplots

I'd like to create a quasi boxplot graph as shown on pages 15/16 of the attached report.
comisef.eu/files/wps031.pdf
Ideally I only want to show the median, the maximum and minimum values as in the report.
I would also like to have similar spacing to that shown in the report.
Currently I have two matrices with the all the necessary values stored in them but have no idea how to do this in matlab.
The boxplot function gives too much data (outliers etc) which makes the resulting graph look confused especially when I try to plot 200 on one page as in the original report.
Is there another function that can so the same thing as in the report in matlab?
Baz
OK here is some test data each row represents 10 sets of estimations of a data set, and each column represents the test number for a given observation.
As boxplot works on the columns of the input matrix you will need to transpose the matrix.
Is it possible to turn outliers and the inter-quartile ranges off? Ideally I just want to see the maximum, minimum and median values?
You can repeat the data below to get up to 200. Or I can send more data if necessary.
0.00160329732202511 0.000859407819412016 0.000859407819411159 0.0659939338995606 0.000859407819416322 0.000859407819416519 2.56395024851142e-15 2.05410662537078e-14 0.000859407819416209
1.67023155116586e-06 8.88178419700125e-16 1.67023155115637e-06 0.000730536218639616 1.67023155105582e-06 3.28746017489609e-15 4.41416632660789e-15 1.67023155094400e-06 1.67023155097567e-06
1.42410590843629e-06 1.42410590840224e-06 1.76149166727218e-15 5.97790925044131e-15 1.42410590843863e-06 2.87802701599909e-15 9.31529385335274e-16 9.17306727455842e-16 0.000820358763518906
8.26849110292527e-16 3.23505095414772e-15 4.38139485761850e-07 4.38139485938112e-07 4.38139485981887e-07 0.000884647755317917 3.72611754134110e-15 4.38139485974329e-07 4.38139485923219e-07
0.000160661751819407 0.000870787937135265 0.000870787937136209 1.16934122581182e-15 9.02860049358913e-16 1.18053134896556e-15 1.40433338743068e-15 0.000870787937135929 1.13510916297112e-15
1.16934122581182e-15 3.80292342262841e-05 3.80292342263200e-05 0.00284904319356532 1.74649997619656e-15 3.80292342264024e-05 0.00284904319356537 1.01267920724547e-15 0.00284904319356540
0.100091800399985 0.100091773169254 0.100091803903140 0.000770464183529358 0.100091812455930 3.49996706323281e-05 3.49996706323553e-05 1.05090687851466e-15 0.100091846333800
0.00100555294602561 0.00100555294601056 0.105365907420183 0.000121078082591672 9.02860049358913e-16 0.000121078082591805 4.49679158258033e-15 7.77684615168284e-16 0.000121078082591693
0.122539456858702 0.000363547764643498 0.000363547764643509 0.122516928568610 0.0101487499394213 0.122408366511784 0.000363547764643519 1.13510916297112e-15 0.122521393586646
0.000460749357561036 0.000460749357560646 3.27600489447913e-13 1.18053134896556e-15 0.000460749357561239 1.54689304063675e-15 0.000460749357560827 0.000460749357561205 1.16934122581182e-15
Instead of using boxplot, I suggest just drawing lines from the min to the max and making a mark at the median. Boxplot draws boxes from the 25 to 75 percentile, which doesn't sound like what you want. Something like this:
% fake data
nPoints = 100;
data = 10*rand(10, nPoints);
% find statistics
minData = min(data, [], 1);
maxData = max(data, [], 1);
medData = median(data);
% x coordinates of each line. Change this to change the spacing.
x = 1:nPoints;
figure
hold on
%plot lines
line([x; x], [minData; maxData])
% plot cross at median
plot(x, medData, '+')
EDIT: To have horizontal lines and a second axis you can do something like this:
figure
h1 = subplot(1,2,1);
h2 = subplot(1,2,2);
% left subplot
axes(h1)
hold on
%plot lines
line([minData; maxData], [x; x])
% plot cross at median
plot(medData, x, '+')
% link the axes so they will have the same limits
linkaxes([h1,h2],'y')
% turn off ticks on y axis.
set(h2, 'YTick', [])
I think it's a question of playing with the settings. You can try:
boxplot(X, 'plotstyle', 'compact', 'colors', 'k', 'medianstyle', 'line', 'outliersize', 0);
Explanation:
'plotstyle', 'compact': makes the boxes filled and the lines undashed
'colors', 'k': color is black
'medianstyle', 'line': the median is marked by a line
'outliersize', 0: if outlier size is zero, you don't see them
Other you can try:
'orientation', 'vertical': this flips the orientation, depends on your data
'whisker', 10 (or higher): this sets the maximum whisker length as a function of the interquartile limits (if you crank it up, it will eventually default to max and min values), I wasn't sure if this is what you wanted. Right now, it goes to the 25th and 75th percentile values.
The spacing is going to depend on how much data you have. If you edit with some data, I can try it out for you.