I am trying to plot a polygon and a line using the code below but the line does not start from 0, 0. Any idea why?
Code:
close all;
clear;
clc;
xLine(1) = 0;
yLine(1) = 0;
xLine(2) = -2;
yLine(2) = -2;
lineseg = [xLine(1), yLine(1); xLine(2), yLine(2)];
P = [0 0; 1 1; 1 0; 0 1; 0 0];
pgon = polyshape(P)
plot(lineseg);
hold on;
plot(pgon);
From the docs for plot
plot(Y) creates a 2-D line plot of the data in Y versus the index of each value.
[...]
If Y is a matrix, then the plot function plots the columns of Y versus their row number. The x-axis scale ranges from 1 to the number of rows in Y.
So you are plotting the row numbers ([1 2]) against the values in each row, in this case twice but the columns of lineseg are equivalent so you don't see that.
You probably want to instead use something like
plot( lineseg(:,1), lineseg(:,2) );
i.e. use the plot(X,Y) form of the plot function
Related
I was thinking of a question similar to this.
I have a function which takes as input the three values x,y,z from the R^3 and returns either 1,2,3,4. Now I wanted to plot the point in the 3D space with coordinates (x,y,z) with a color associated with the functional value at that point which can be either one of 1,2,3 or 4.
I have a 3D matrix with integer entries like say 1,2,3,4 and I store the points value in this matrix so that I can plot the points with the corresponding color (similar trick of 'image' command in MATLAB for making 2D plots).
color coding (say)-
1 - green, 2 - blue , 3 - cyan , 4 -red
Like if at the point (0.5,0.5,0.1) the function returns the value 3, then I mark the point (0.5,0.5,0.1) with the color associated to number three which is cyan.
I am thinking of a MATLAB command which does this in the case of three dimensional case as the "image" command seems to work for the 2D case.
I can only think of some kind of workaround, like this:
% Input: A = coordinates, b = functional values.
A = rand(20, 3);
b = ceil(rand(20, 1) * 4);
% Color map.
cm = [0 1 0; 0 0 1; 0 1 1; 1 0 0];
% Circle size.
cs = 21;
% 3D scatter plot.
figure(1);
hold on;
for k = 1:size(cm, 1)
idx = (b == k);
scatter3(A(idx, 1), A(idx, 2), A(idx, 3), cs, cm(k, :), 'filled');
end
hold off;
view(45, 30);
grid on;
Gives the following output:
You can linearize the solution suggested by #HansHirse, so a small improvement could be:
% Dummy data
A = rand(20, 3);
b = ceil(rand(20, 1) * 4);
% color vector
c = [0 1 0; 0 0 1; 0 1 1; 1 0 0];
% Use the linear indexing to select the right color
scatter3(A(:,1),A(:,2),A(:,3),[],c(b,:),"filled")
Even simpler you can just use b as color input and matlab will use the default colormap to set the color according to b
scatter3(A(:,1),A(:,2),A(:,3),[],b,"filled")
So essentially I have this code here that I can use to generate a 2D Random Walk discretely along N number of steps with M number of walkers. I can plot them all on the same graph here.
clc;
clearvars;
N = 500; % Length of the x-axis, also known as the length of the random walks.
M = 3; % The amount of random walks.
x_t(1) = 0;
y_t(1) = 0;
for m=1:M
for n = 1:N % Looping all values of N into x_t(n).
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
x_t(n+1) = x_t(n) + A;
A = sign(randn); % Generates either +1/-1 depending on the SIGN of RAND.
y_t(n+1) = y_t(n) + A;
end
plot(x_t, y_t);
hold on
end
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0.05, 1, 0.95]);
axis square;
Now, I want to be able to Create graphs that show the distribution in space of the positions of a large number
(e.g. n = 1000) random walkers, at three different time points (e.g. t = 100, 200 and 300 or any three time points really).
I'm not sure how to go about this, I need to turn this into a function and iterate it through itself three different times and store the coordinates? I have a rough idea but iffy on actually implementing. I'd assume the safest and least messy way would be to use subplot() to create all three plots together in the same figure.
Appreciate any assistance!
You can use cumsum to linearize the process. Basically you only want to cumsum a random matrix composed of [-1 and 1].
clc;
close all;
M = 50; % The amount of random walks.
steps = [10,200,1000]; % here we analyse the step 10,200 and 1000
cc = hsv(length(steps)); % manage the color of the plot
%generation of each random walk
x = sign(randn(max(steps),M));
y = sign(randn(max(steps),M));
xs = cumsum(x);
xval = xs(steps,:);
ys = cumsum(y);
yval = ys(steps,:);
hold on
for n=1:length(steps)
plot(xval(n,:),yval(n,:),'o','markersize',1,'color',cc(n,:),'MarkerFaceColor',cc(n,:));
end
legend('10','200','1000')
axis square
grid on;
Results:
EDIT:
Thanks to #LuisMendo that answered my question here, you can use a binomial distribution to get the same result:
steps = [10,200,10000];
cc = hsv(length(steps)); % manage the color of the plot
M = 50;
DV = [-1 1];
p = .5; % probability of DV(2)
% Using the #LuisMendo binomial solution:
for ii = 1:length(steps)
SDUDx(ii,:) = (DV(2)-DV(1))*binornd(steps(ii), p, M, 1)+DV(1)*steps(ii);
SDUDy(ii,:) = (DV(2)-DV(1))*binornd(steps(ii), p, M, 1)+DV(1)*steps(ii);
end
hold on
for n=1:length(steps)
plot(SDUDx(n,:),SDUDy(n,:),'o','markersize',1,'color',cc(n,:),'MarkerFaceColor',cc(n,:));
end
legend('10','200','1000')
axis square
grid on;
What is the advantage ? Even if you have a big number of steps, let's say 1000000, matlab can handle it. Because in the first solution you have a bruteforce solution, and in the second case a statistical solution.
If you want to show the distribution of a large number, say 1000, of these points, I would say the most suitable way of plotting is as a 'point cloud' using scatter. Then you create an array of N points for both the x and the y coordinate, and let it compute the coordinate in a loop for i = 1:Nt, where Nt will be 100, 200, or 300 as you describe. Something along the lines of the following:
N = 500;
x_t = zeros(N,1);
y_t = zeros(N,1);
Nt = 100;
for tidx = 1:Nt
x_t = x_t + sign(randn(N,1));
y_t = y_t + sign(randn(N,1));
end
scatter(x_t,y_t,'k*');
This will give you N x and y coordinates generated in the same way as in the sample you provided.
One thing to keep in mind is that sign(0)=0, so I suppose there is a chance (admittedly a small one) of not altering the coordinate. I am not sure if you intended this behaviour to be possible (a walker standing still)?
I will demonstrate the 1-dimensional case for clarity; you only need to implement this for each dimension you add.
Model N steps for M walkers using an NxM matrix.
>> N = 5;
>> M = 4;
>> steps = sign(randn(N,M));
steps =
1 1 1 1
-1 1 -1 1
1 -1 -1 -1
1 1 -1 1
1 -1 -1 -1
For plotting, it is useful to make a second NxM matrix s containing the updated positions after each step, where s(N,M) gives the position of walker M after N steps.
Use cumsum to vectorize instead of looping.
>> s = cumsum(steps)
s =
1 1 1 1
0 2 0 2
1 1 -1 1
2 2 -2 2
3 1 -3 1
To prevent plot redraw after each new line, use hold on.
>> figure; hold on
>> plot(1:N, s(1:N, 1:M), 'marker', '.', 'markersize', 20, 'linewidth', 3)
>> xlabel('Number of steps'); ylabel('Position')
The output plot looks like this: picture
This method scales very well to 2- and 3-dimensional random walks.
Basically the problem I can't solve is how to adapt into a for loop so depending on whatever dimensions I am given it does it on its own. This is an example using 2x2 dimensions. So for example if was to do 3x3 how would I do it in a for loop?
N=4;
R=2;
theta=zeros(1,N);
for k=1:N
theta(k)=2*pi*(k-1)/N;
end
x1=(R*cos(theta+pi/4)/sqrt(2));
y1=(R*sin(theta+pi/4)/sqrt(2));
plot(x1,y1);
fill(x1,y1,'w');
x2=(R*cos(theta+pi/4)/sqrt(2))+R;
y2=(R*sin(theta+pi/4)/sqrt(2));
plot(x2,y2);
fill(x2,y2,'y');
x3=(R*cos(theta+pi/4)/sqrt(2));
y3=(R*sin(theta+pi/4)/sqrt(2))+R;
plot(x3,y3);
fill(x3,y3,'y');
x4=(R*cos(theta+pi/4)/sqrt(2))+R;
y4=(R*sin(theta+pi/4)/sqrt(2))+R;
plot(x4,y4);
fill(x4,y4,'w');
hold;
You could set up a grid of points using ndgrid (or meshgrid).
To create index for the checker pattern, one trick is to use invhilb.
Below I used constant x and y instead of the one you created from R*cos(theta+pi/4)/sqrt(2)
% User input
N = 4;
% Basic square index
x = [0 1 1 0];
y = [0 0 1 1];
% Create axes and set to 'hold'
axes('NextPlot','Add')
% Create grid
[X,Y] = ndgrid(0:N-1);
% Loop over grid
for idx = 1:numel(X)
fh(idx) = fill(X(idx) + x, Y(idx) + y, 'w');
end
% Color as a check board (but with yellow)
set(fh(invhilb(N) > 0),'FaceColor','y')
I have been struggling with this problem for a while and I would appreciate if anyone can help me out. I am able to generate a 10 by 10 matrix and have it randomly assign "1"s in the matrix. My goal is to plot a "star" at the location of each element in the vector that has a value of "1", but I can't seem to figure out how to map the vector to a x-y coordinate system. The code I wrote below generates a plot of 100 stars at each cell and also generates a vector "v", but I don't know how I can link the plot to the vector that instead of having 100 "star"s in my plot, I have however many that there is a value of "1" at the corresponding location of the element.
Thanks!!
David
davidtongg#gmail.com
close all
clear all
clc
a=10;b=10;
v = zeros(a,b);
xy = int32(randi(a, 100, 2));
z = randi(1, 100, 1); % 100 values.
indexes = sub2ind([a, b], xy(:,1), xy(:,2))
v(indexes) = z
m=length(v);
ctr=0;
for i=1:m^2
x_cor(i)=(i-(floor(i/m)*m))*200-100;
y_cor(i)=(floor(i/m)+1)*200-100;
for j=1:m
if i==j*m
x_cor(i)=((i-(floor(i/m)*m))*200-100)+(2*m*100);
y_cor(i)=(floor(i/m))*200-100;
end
end
end
figure(1)
plot(x_cor,y_cor,'*');
grid on
I may of course have misinterpreted this because that code is confusingly complicated, but this is what I think you're after.
For an axb matrix with a random number of ones:
v = randi([0 1], a, b);
Or for a specific number n of ones, in random locations:
v = zeros(a, b);
idx = randi([1 numel(v)], n, 1);
v(idx) = 1; % linear indexing into a matrix
Then to plot them in arbitrarily scaled coordinates:
[y x] = find(v);
x = x * xscale + xoffset;
y = y * yscale + yoffset;
plot(x, y, '*');
Or the really cheaty way:
spy(v);
You can do it easily taking into account that plot(A) , where A is a matrix, plots the columns of the matrix vs their index, and that NaNs are not plotted:
v =[ 1 0 0 0
1 1 0 0
0 0 0 1
1 1 1 1
0 1 1 0 ]; %// example data
v2 = double(v); %// create copy; will be overwritten
v2(~v2) = NaN; %// change zeros to NaNs
plot(bsxfun(#plus, fliplr(v2.'), 0:size(v,1)-1) ,'b*')
%'// transpose and flip from left to right.
%// Add 1 incrementally to each column to have all of them "stacked" in the plot
axis([0 size(v,2)+1 0 size(v,1)+1]) %// set axis limits
set(gca,'xtick',1:size(v,2),'ytick',1:size(v,1)) %// set ticks
grid
I'm new to Matlab but I know a bit about programming.
For class, we have been asked to generate a matrix that gives the vertices of a two dimensional n-sided shape where n>=4. Then, generate the vectors to connect the vertices. We were also given a hint: a vector for each segment can be found by adding the vectors drawn from the origin to each of two adjacent vertices.
I know how to create a matrix using A = [1 1; 1 2; 2 2; 2 1] but I'm not sure how to draw the vectors given this or any other matrix.
The plot() function looks promising, but I'm unsure how to use it with the matrix.
Thank you for any suggestions.
Btw, I'm using Matlab 2011a
I'm not exactly sure how your matrix represents your shape but you might for example let the x-coordinates of the shape be the first column of your array, then let the y-coordinates be the 2nd column, like:
A = [1 1; 1 2; 2 2; 2 1];
x = A(:,1);
y = A(:,2);
fill(x,y,'g');
axis([0 3 0 3]);
axis square;
Which in your case plots a square from the matrix A:
Or construct something a little more complicated like a pentagon:
theta = [0:pi/2.5:2*pi];
x = sin(theta);
y = cos(theta);
% your matrix is then:
B(:,1) = x;
B(:,2) = y;
B
figure;fill(x,y,'g');
axis square;
Which gives:
If you just want to plot the outline with plot (not fill the interior with fill), just remember you have to repeat the initial point at the end so that the polygonal line is closed:
A = [1 1; 1 2; 2 2; 2 1];
B = [A; A(1,:) ]; %// repeat first row at the end
plot(B(:,1),B(:,2))
axis equal %// same scale on both axes
axis([min(x)-.5 max(x)+.5 min(y)-.5 max(y)+.5]) %// larger axes for better display