How to get random points from upper semisphere

1 回表示 (過去 30 日間)
Mojtaba Mohareri
Mojtaba Mohareri 2020 年 8 月 19 日
コメント済み: Mojtaba Mohareri 2020 年 8 月 19 日
Hello eveyone,
I use this code to get random points from a sphere with radius 5:
clear all
clc
fullFileName = fullfile(pwd, 'DataPoints.txt')
% Open a text file.
fileHandle = fopen(fullFileName, 'wt');
% Write out the things we want to write out.
rng(0,'twister')
rvals = pi*rand(100,1)+pi/2;
azimuth = 2*pi*rand(100,1);
[x,y,z] = sph2cart(azimuth,rvals,5);
figure
plot3(x,y,z,'.')
axis equal
fprintf(fileHandle, '{%f, %f ,%f},',[x,y,z]');
fprintf(fileHandle, '[%f, %f ,%f],',[x,y,z]');
fprintf(fileHandle, '%f, %f , %f;',[x,y,z]');
% Close the file.
fclose(fileHandle);
% Open it in notepad (Windows OS only)
winopen(fullFileName);
, but I want to have random points from upper semisphere with this radius.
Thanks in advance.

採用された回答

Bruno Luong
Bruno Luong 2020 年 8 月 19 日
Put
...
[x,y,z] = sph2cart(azimuth,rvals,5);
z = abs(z)
...
  1 件のコメント
Mojtaba Mohareri
Mojtaba Mohareri 2020 年 8 月 19 日
Thank you very very much.

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

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 8 月 19 日
編集済み: Bruno Luong 2020 年 8 月 19 日
Your code won't generate uniform point on half sphere, there is a bigger density on the north pole (try to generate with 10000 points you'll see).
A better approach would be
radius = 5;
xyz = randn(3,100);
xyz = xyz .* (radius ./ sqrt(sum(xyz.^2,1)));
x = xyz(1,:);
y = xyz(2,:);
z = abs(xyz(3,:));
  3 件のコメント
Bruno Luong
Bruno Luong 2020 年 8 月 19 日
You have very old matlab version, replace with
xyz = bsxfun(@times, xyz, radius ./ sqrt(sum(xyz.^2,1)));
Mojtaba Mohareri
Mojtaba Mohareri 2020 年 8 月 19 日
Yes, unfortunately it's MATLAB R2015a. It's works properly. Thank you very very much.

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

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by