Changing the coordinates using a vector - matlab

Let's say I am at the point (0, 0) in MATLAB and I want to move in the coordinate plane, let's say by the vector [1, 1]. Clearly, I could just manually add 1 and 1 to the x and y coordinates, or I could set v = [1, 1] and increment x by v(1) and y by v(2) or something along those lines. However, let's say I didn't want to do this. For example, suppose my aim is to plot the graph generated by the following algorithm.
Start at the point (0, 0)
Alternate between the displacement vectors (1, 1) and (1, -1) until you reach (100, 0).
Graph it.
How would I do this using the vector directly? In other words, is there something in MATLAB which allows you to directly do something like position = current position + vector? Thanks!

Here is a way to do it from what I understood:
clc
clear
%// The 2 displacement vectors
d1 = [1 1];
d2 = [1 -1];
%// Create a matrix where each row alternates between d1 and d2.
%// In the following for-loop we will access each row one by one to create the displacement.
D = repmat([d2;d1],51,1);
%/ Initialize matrix of positions
CurrPos = zeros(101,2);
%// Calculate and plot
hold all
for k = 2:101
CurrPos(k,:) = CurrPos(k-1,:) + D(k,:); %// What you were asking, I think.
%// Use scatter to plot.
scatter(CurrPos(k,1),CurrPos(k,2),40,'r','filled')
end
box on
grid on
And the output:
Is this what you had in mind?

Related

Rotate discrete dataset Octave

I have a discrete dataset, X=[x1,x2,..,x12] & Y=[y1,y2,...,y12]. X ranges from [-25, 0] and Y ranges from [1e-6, 1e0]. X does not increase uniformly - as x approaches a value of 0, data sampling density increases from increments of 2.5 to increments of 1. Each x value is units of cm. I cannot get a good fit to the data from fitting a function (I've tried quite a few). I'm left with the discrete data. My need is to sweep the X, Y data completly around the Z axis and put the resulting swept data values into a matrix Z of size (51, 51). I've tried using the cylinder function, [u,v,w] = cylinder(Y) thinking I could extract the data or create a matrix Z from [u, v, w]. I can't seem to sort that out. surf(u,v,w) plots almost correctly - the scaling on the (u, v) axes ranges from [-1, 1] instead of [-25, 25]. This is, I assume, because I'm using cylinder(Y). When I try [u,v,w] = cylinder(X,Y) I get, error: linspace: N must be a scalar. It seems like there should be a better way then my approach of using cylinder to take the X & Y data, interpolate between points (to fill Z where data isn't), rotate it, and put the result into a matrix Z. Any suggestions are welcome. I'm using Octave 6.3.0. Thank you in advance.
Create a matrix R containing distance from origin values.
Use for loops and single value interpolation to cover the R space.
Place the interpolated values into the matrix Z.
% Original data X = [-25,-22.5,...,0]; size(X) = 1 12
% Original data Y = [1e-6, 1.3e-6,...,1] size(Y) = 1 12
u = [-range(X):1:range(X)]; v = [-range(X):1:range(X)]';
R = -sqrt(u.^2.+v.^2);
Z = zeros( 2 .* range(X) + 1);
for i = 1:size(R,1)
for j = 1:size(R,2)
if R(i,j) < min(X); Z(i,j) = 0; endif
if R(i,j) >= min(X); Z(i,j) = interp1(X,Y,R(i,j)); endif
endfor
endfor

Volumetric 3D data plotting from 2D map in MATLAB?

I have a heat map
and want to convert this 2D matrix to a 3D volume/shape/surface data points for further processing. Not simply display it in 3D using surf.
What would be a good way to do this?
With a lot of help from this community I could come closer:
I shrunk the size to 45x45 px for simplicity.
I = (imread("TESTGREYPLASTIC.bmp"))./2+125;
Iinv = 255-(imread("TESTGREYPLASTIC.bmp"))./2-80;%
for i = 1:45
for j = 1:45
A(i, j, I(i,j) ) = 1;
A(i, j, Iinv(i,j) ) = 1;
end
end
volshow(A)
Its not ideal but the matrix is what I wanted now. Maybe the loop can be improved to run faster when dealing with 1200x1200 points.
How do I create a real closed surface now?
Following your conversation with #BoilermakerRV, I guess you are looking for one of the following two results:
A list of 3d points, where x and y are index of pixels in the image, and z is value of corresponding pixels. The result will be an m*n by 3 matrix.
An m by n by 256 volume of zeros and ones, that for (i,j)-th pixel in the image, all voxels of the (i, j)-the pile of the volume are 0, except the one at I(i, j).
Take a look at the following example that generates both results:
close all; clc; clear variables;
I = rgb2gray(imread('data2.png'));
imshow(I), title('Data as image')
% generating mesh grid
[m, n] = size(I);
[X, Y] = meshgrid(1:n, 1:m);
% converting image to list of 3-d points
P = [Y(:), X(:), I(:)];
figure
scatter3(P(:, 1), P(:, 2), P(:, 3), 3, P(:, 3), '.')
colormap jet
title('Same data as a list of points in R^3')
% converting image to 256 layers of voxels
ind = sub2ind([m n 256], Y(:), X(:), I(:));
V = zeros(m, n, 256);
V(ind) = 1.0;
figure
h = slice(V, [250], [250], [71]) ;
[h.EdgeColor] = deal('none');
colormap winter
camlight
title('And finally, as a matrix of 0/1 voxels')
The contour plot that is shown can't be generated with "2D" data. It requires three inputs as follows:
[XGrid,YGrid] = meshgrid(-4:.1:4,-4:.1:4);
C = peaks(XGrid,YGrid);
contourf(XGrid,YGrid,C,'LevelStep',0.1,'LineStyle','none')
colormap('gray')
axis equal
Where XGrid, YGrid and C are all NxN matrices defining the X values, Y values and Z values for every point, respectively.
If you want this to be "3D", simply use surf:
surf(XGrid,YGrid,C)

Creating graphs that show the distribution in space of a large number of 2D Random Walks at three different time points

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.

MatLab--How would I generate an n-sided shape wher n >= 4

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

Plot lines between points in a matrix in MATLAB

I have a matrix with n rows and 4 columns. The columns are x0, y0, and x1, y1 (so basically I have n pairs of point coordinates in 2D). I want to draw a line between corresponding point pairs (that is, only between x0, y0 and x1, y1 of one row).
Is it possible to do it without a loop? Because the following works but is very slow.
for i = 1:size(A.data, 1)
plot([A.data(i, 1), A.data(i, 3)], [A.data(i, 2), A.data(i, 4)], 'k-')
end
I came here looking for the same answer. I basically want a horizontal line for each x,y point, starting with that point's x-y value, and ending at the x value of the next xy pair, without a line joining that segment to that of the next xy pair. I can make the segments by adding new points between, with the old y and the new x, but I didn't know how to break up the line segments. But your wording (matrix) gave me an idea. What if you load your xy pairs to a pair of x, y vectors and - wait for it - separate your pairs with nan's in both the x and y vectors. I tried that with a very long sine wave, and it seems to work. A ton of disjoint line segments, that plot and zoom instantly. :) See if it solves your problem.
% LinePairsTest.m
% Test fast plot and zoom of a bunch of lines between disjoint pairs of points
% Solution: put pairs of x1,y1:x2,y2 into one x and one y vector, but with
% pairs separated by x and or y = nan. Nan is wonderful, because it leaves
% your vector intact, but it doesn't plot.
close all; clear all;
n = 10000; % lotsa points
n = floor(n/3); % make an even set of pairs
n = n * 3 - 1; % ends with a pair
x = 1:n; % we'll make a sine wave, interrupted to pairs of points.
% For other use, bring your pairs in to a pair of empty x and y vectors,
% padding between pairs with nan in x and y.
y = sin(x/3);
ix = find(0 == mod(x,3)); % index 3, 6, 9, etc. will get...
x(ix) = nan; % nan.
y(ix) = nan; % nan.
figure;
plot(x,y,'b'); % quick to plot, quick to zoom.
grid on;
This works for the data structure I have:
data = [
0, 0, 1, 0;...
1, 0, 1, 1;...
1, 1, 0, 1;...
0, 1, 0, 0 ...
];
figure(1);
hold off;
%slow way
for i = 1:size(data, 1)
plot([data(i, 1) data(i, 3)], [data(i, 2) data(i, 4)], 'r-');
hold on;
end
%fast way ("vectorized")
plot([data(:, 1)' data(:, 3)'], [data(:, 2)' data(:, 4)'], 'b-');
axis equal
This particular example draws a square.
The key is that MATLAB draws lines column-wise in the arguments. That is, if the arguments of plot have n columns, the line will have n-1 segments.
In a "connect-the-dots" scenario where all points in the vectors must be connected, this is irrelevant because MATLAB will transpose to get a column vector if it needs to. It becomes important in my application because I do not want to connect every point on the list - only pairs of points.
Try line for example
X=[1:10 ; 2*(1:10)];
Y=fliplr(X);
line(X,Y)