How to sort points for plotting in MATLAB?

45 ビュー (過去 30 日間)
Ángel González
Ángel González 2018 年 8 月 23 日
編集済み: MathWorks Support Team 2020 年 9 月 3 日
Hello! I've got a little question about plotting points. In my project, I'm getting x and y coordinates and plotting them just when I read them from the socket, and I get something like this:
Just after plotting the coordinates I'm indexing them in two different vectors (one for x coordinates and the other for y coordinates). The problem is, when I try to plot them again in another script (or in another figure) the result is not what I expected.
The code I use for plotting the points the second time is:
figure()
for i=1:1000 %1000 is the length of x_vector and y_vector
plot(x_vector(i), y_vector(i), 'o')
hold on
axis([0 1920 0 1080]);
set(gca, 'ydir', 'reverse', 'xaxislocation', 'top')
end
And this is the result of the previous code:
I guess that the second time I try to plot the two vectors plot is trying to print some linear function through some regression instead of printing the cloud of points I expect.
Thank you
  11 件のコメント
Jan
Jan 2018 年 8 月 23 日
Maybe replace
x_vector = sort([x_vector x]);
y_vector = sort([y_vector y]);
by
[x_vector, index] = sort([x_vector x]);
yTemp = [y_vector y];
y_vector = yTemp(index);
dpb
dpb 2018 年 8 月 23 日
That's calling sort repetitively every iteration...there's no indication of needing them sorted; if do, far more efficient to wait until done collecting and then sort the whole vector once.
Keeping and reordering y based on order of sorted x is, of course, necessry to keep the association between the two.
Alternatively, one could do slightly differently as
xy=[];
while collecting()
% get x, y
xy=[xy; [x y]];
...
end
xy=sortrows(xy);
and will have x,y in two columns in the one arrray sorted by increasing x

サインインしてコメントする。

採用された回答

Ángel González
Ángel González 2018 年 8 月 23 日
Thank you all for helping me. As you said, the problem was how I was storing the coordinates. This comment from @dpb resumed the problem perfectly: https://es.mathworks.com/matlabcentral/answers/416020-how-can-i-plot-points-in-matlab#comment_602802
  1 件のコメント
dpb
dpb 2018 年 8 月 23 日
You're welcome... :)

サインインしてコメントする。

その他の回答 (1 件)

Afshin Aghayan
Afshin Aghayan 2019 年 10 月 9 日
you can use this code for displaying any data in the form of [x, y, f(x,y)] or data with coordinate

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by