plotting lines as separate objects

Hi Guys, I am new to matlab and I am trying to plot the following points. The first column represents x values and the second column represents y values. If I plot(x,y), matlab plots all the points as one continuous line. But what I want is different lines separated by the NaN like shown above. For example, I want first four (x,y) points to be one separate line, the next three (x,y) points to be another line and so on... I want to plot these lines separately because I need to find the centroid of each lines (actually these are curves).
Can anyone help, please?
Thank you!

 采纳的回答

Try this (substituting your own data matrix for ‘D’ here):
D = sort(rand(30,2)); % Create Data
D([5 12 22],1) = NaN; % Create Data (Insert ‘NaN’ Values)
brk = diff([0; find(isnan(D(:,1))); size(D,1)]); % Find ‘NaN’ Rows
Dc = mat2cell(D, brk, 2); % Convert To Cell Arrays
Dc(1:end-1) = cellfun(@(x) x(1:end-1,:), Dc(1:end-1), 'Uni',0); % Delete Last Row ([NaN NaN]) Of All But The Last Cell
figure
hold all
for k1 = 1:size(Dc,1)
plot(Dc{k1}(:,1), Dc{k1}(:,2))
end
grid
hold off
hold off
It first detects the NaN rows, segments the data into cell arrays using mat2cell, and then plots the cells in the loop.
EDIT — To calculate the centroids (the arithmetic mean of each column of each group):
Cntrds = cellfun(@mean, Dc, 'UniformOutput',false);
and to plot them and the centroids:
figure
hold all
for k1 = 1:size(Dc,1)
plot(Dc{k1}(:,1), Dc{k1}(:,2))
plot(Cntrds{k1}(:,1), Cntrds{k1}(:,2), 'p')
end
grid
hold off

4 个评论

Thank you Star Strider, I see separate curves now. Could you please explain how brk variable is calculated? The brk's output is 5 7 10 8, I am not sure how it works?
My pleasure.
The mat2cell function requires that the matrices be divided so that the total dimensions of the segments equals the dimensions of the original matrix. The ‘brk’ (‘break’) variable does this by subtracting the NaN positions from each other (in the diff call, appending the beginning 0 and end ‘size(D,1)’ values).
I created ‘D’ by inserting NaN values at 5, 12, and 22, and the differences between ‘[0 5 12 22 30]’ are the values returned by ‘brk’. The diff function calculates 5-0, 12-5, 22-12 and 30-22. It then uses those values to create separate matrices with the mat2cell function.
That is as much of an explanation as I can provide.
Great! it works. I want to find the closest distance from one centroid to another centroid for all centroids. Could you please help?
As always, my pleasure!
See if the Statistics and Machine Learning Toolbox function pdist (link) or pdist2 (link) will do what you want. Note that you will also need the squareform (link) function to make their results intelligible.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by