How to count the lines crossing the y axis?

7 ビュー (過去 30 日間)
Maaz Madha
Maaz Madha 2019 年 3 月 29 日
コメント済み: Star Strider 2019 年 3 月 29 日
Hi.
In my project I have to plot 50 lines randomly(length 3 and random angle) and to count the number of lines crossing the the y axis(y=0) and then compare the lines crossing the y axis. I have used for loops and managed to plot the 50 lines with length 3 and various angles but am struggling to count the number of lines crossing the y axis.
Thank you for any help
  2 件のコメント
Jan
Jan 2019 年 3 月 29 日
The y-axis is not "y=0", but "x=0". What does "then compare the lines crossing the y axis" mean? Compare with what?
Maaz Madha
Maaz Madha 2019 年 3 月 29 日
yes you are correct im a fool it is meant to be x=0. What I meant was that find the ratio of the lines crossing x=0 vs the total lines there are(50)

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

回答 (2 件)

Jan
Jan 2019 年 3 月 29 日
編集済み: Jan 2019 年 3 月 29 日
If you want to identify if a line crosses the y axis, check if the x component of the start point has another sign than the end point.
sum(sgn(x1) == sgn(x2)) / numel(x1) % Ratio of lines crossing y axis
Note that this catchs also line touching the y axis. Here I assume, that x1 contains the x positions of the startpoint and x2 the end poisitions.

Star Strider
Star Strider 2019 年 3 月 29 日
Try this:
x = randi([-10 10], 50, 2); % X-Coordinates
y = randi([-10 10], 50, 2); % Y-Coordinates
crossYaxis = nnz(prod(x,2) <= 0) % Number Of Lines Crossing Y-Axis
figure
hold all
for k = 1:size(x,1)
plot(x(k,:), y(k,:))
end
grid
Experiment to get the result you want.
  2 件のコメント
Maaz Madha
Maaz Madha 2019 年 3 月 29 日
What does nnz(prod(x,2) <= 0) mean? What does prod(x,2) do etc
for k = 1:size(x,1)
plot(x(k,:), y(k,:)) also can you elaborate on what this means plz
Star Strider
Star Strider 2019 年 3 月 29 日
The nnz function counts the number of non-zero values in an array.
The ‘prod(x,2)’ call takes the product of the ‘x’ matrix across the rows (the second dimension in MATLAB), multiplying the first column by the second column element-wise.
The plot call here in the loop plots the lines individually, rather than as one continuous line. The plot call is optional

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

カテゴリ

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

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by