Reputation: 137
I want to display points in a 30x30 grid at random whenever my code is run, there are 10 points in total. The 10 points will be plotted in a area 30 by 30 defined as A1. x going from 0 to 30 and y going from 0 to 30. I want the coordinates of these 10 points
A1 = 30; % area defined as 30 X 30 grid
N = 10; % 10 tags
% Generate x and y position of tags
for ii = 1:N
xtemp = A1*rand(1,1);
ytemp = A1*rand(1,1);
end
plot (xtemp,ytemp)
grid on
When I run the code i get more than ten points, what i want is just 10 points on the graph and the co-ordinates of each random point chosen to be displayed. The code only seems to work when the matrix is not (1,1)
Upvotes: 2
Views: 102
Reputation: 112699
You don't need the loop. It is doing the same in each iteration, and you are only using the result of the last iteration.
To plot individual points, use a mark such as '.'
or 'o'
. This is passed as a third argument to plot
:
A1 = 30;
N = 10;
xtemp = A1*rand(1,N);
ytemp = A1*rand(1,N);
plot(xtemp, ytemp, '.')
grid on
axis([0 A1 0 A1])
To add text labels showing each point's coordinates:
xoffset = 0;
yoffset = -1;
fsize = 8;
temp_str = mat2cell(num2str([xtemp(:) ytemp(:)], '(%.2f,%.2f)'), ones(1,N));
text(xtemp+xoffset, ytemp+yoffset, temp_str, 'fontsize', fsize)
You may want to change the format specifier '(%.2f,%.2f)'
; xoffset
and yoffset
to control label position; and fsize
to define font size. Note that it's likely that some labels partially overlap. You can reduce the chance of overlapping using smaller values of fsize
.
Upvotes: 3