While Plotting x-y contour, it plot a single point - matlab

I have tried many times to create an x and y plot.
Every time I get only a point, and not a contour which I want. It should be the arc of a circle or an ellipse.
My current Matlab code:
a = 8*pi/5;
u = 1;
z=0.15;
x = cosh(u)*sqrt(1 - (sin(a)*sin(a)*sinh(u)*sinh(u))/square((sqrt(1-z)*cosh(u) + cos(a))));
y= -1*((sinh(u)*sinh(u)*sin(a))/(sqrt(1-z)*cosh(u) + cos(a)));
plot(x,y,'o')
assume any value of u.

u is a scalar, so you are plotting single points.
Make u an array
a = 8*pi/5;
u = 1:0.02:2; % Your u values as an array
z = 0.15;
And make your operations element-wise in the x and y calculations
x = cosh(u).*sqrt(1 - (sin(a).*sin(a).*sinh(u).*sinh(u))./square((sqrt(1-z).*cosh(u) + cos(a))));
y= -1.*((sinh(u).*sinh(u).*sin(a))./(sqrt(1-z).*cosh(u) + cos(a)));
Use a line style which isn't just a point (like 'o' is), for instance for a line with circles at each value you can use
plot(x,y,'-o')
Note: your x and y calculations give complex results for these values, and plot ignores imaginary parts of the inputs by default.

I forgot u should be an array to get the points in the plot
a = 8*pi/5;
% assigning an array from 1 to 2 with stepsize = 0.1
u = 1:0.02:2;
z = 0.15;
Since, u is an array the multiplication should be element-wise(.*)
x = cosh(u).*sqrt(1 - (sin(a).*sin(a).*sinh(u).*sinh(u))./square((sqrt(1-z).*cosh(u) + cos(a))));
y= -1.*((sinh(u).*sinh(u).*sin(a))./(sqrt(1-z).*cosh(u) + cos(a)));
% Ignoring the complex value since it only provide some phase
plot(abs(x),abs(y),'r');
hold on
plot(real(x),real(y),'g')
legend('abs values','real Values')

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

How plot a two-dimensional function in three-dimensional space with MATLAB?

I want to plot a two-dimensional function of the polar coordinates r and theta in three-dimensional cartesian coordinates. I have that (sorry about bad maths formatting, LaTeX not compatible, it seems)
f(r,theta) = r/2 * (cos(theta - pi/4) + sqrt(1 + 1/2 * cos(2*theta)))
Converting r and theta to cartesian coordinates
x = r * cos(theta), y = r * sin(theta)
Further, the domain is -1<r<1 and 0<theta<2 * pi, which I define by
r = -1:2/50:1;
and
theta = 0:2*pi/50:2*pi;
giving me two vectors of the same dimensions.
I can define the x and y values used for plotting as row vectors by
x = r. * cos(theta);
and
y = r. * sin(theta);
So now I need to define the z values, which will depend on the values of x and y. I thought I should make a 101x101 where each matrix element contains a data point of the final surface. But how should I do this? I thought about using a double for loop:
for i=1:numel(r)
for j=1:numel(theta)
z(i,j) = r(i)/2 .* cos(theta(j) - pi/4) + r(i).*sqrt(1 + 1/2 * cos(2.*theta(j)));
end
end
Then simply surf(z)
While this definitely gives me a surface, it gives me the incorrect surface! I don't know what is happening here. The incorrect surface is given in Figure 1, while the correct one is given in Figure 2. Can anyone help me out? For reference, the correct surface was plotted with GeoGebra, using
A = Function[<expression 1>, <Expresison 2>, <Expression 3>, <var 1>, <start>, <stop>, <var 2>, <start>, <stop>]
Figure 1. Incorrect surface.
Figure 2. Correct surface.
As others have said, you can use meshgrid to make this work.
Here's your example using gridded r and theta and an anonymous function to replace the double loop:
r = -1:2/50:1;
theta = 0:2*pi/50:2*pi;
% define anonymous function f(r,theta)
f = #(r,theta) r/2 .* (cos(theta - pi/4) + sqrt(1 + 1/2 .* cos(2.*theta)));
% generate grids for r and theta
[r, theta] = meshgrid(r,theta);
% calculate z from gridded r and theta
z = f(r,theta);
% convert r,theta to x,y and plot with surf
x = r.*cos(theta);
y = r.*sin(theta);
surf(x,y,z);
You need to use meshgrid to get matrix coordinates if you want to use surf. Taking your x and y (lower case), call
[X,Y] = meshgrid(x,y);
Then X and Y (upper case) will have the same values as you gave it, but laid out in the two-dimensional array as expected by surf. Loop over the indices here and compute your Z, which should have all(size(Z) == size(X)).
https://www.mathworks.com/help/matlab/ref/meshgrid.html

Equally spaced points in a contour

I have a set of 2D points (not ordered) forming a closed contour, and I would like to resample them to 14 equally spaced points. It is a contour of a kidney on an image. Any ideas?
One intuitive approach (IMO) is to create an independent variable for both x and y. Base it on arc length, and interpolate on it.
% close the contour, temporarily
xc = [x(:); x(1)];
yc = [y(:); y(1)];
% current spacing may not be equally spaced
dx = diff(xc);
dy = diff(yc);
% distances between consecutive coordiates
dS = sqrt(dx.^2+dy.^2);
dS = [0; dS]; % including start point
% arc length, going along (around) snake
d = cumsum(dS); % here is your independent variable
perim = d(end);
Now you have an independent variable and you can interpolate to create N segments:
N = 14;
ds = perim / N;
dSi = ds*(0:N).'; %' your NEW independent variable, equally spaced
dSi(end) = dSi(end)-.005; % appease interp1
xi = interp1(d,xc,dSi);
yi = interp1(d,yc,dSi);
xi(end)=[]; yi(end)=[];
Try it using imfreehand:
figure, imshow('cameraman.tif');
h = imfreehand(gca);
xy = h.getPosition; x = xy(:,1); y = xy(:,2);
% run the above solution ...
Say your contour is defined by independent vector x and dependent vector y.
You can get your resampled x vector using linspace:
new_x = linspace(min(x),max(x),14); %14 to get 14 equally spaced points
Then use interp1 to get new_y values at each new_x point:
new_y = interp1(x,y,new_x);
There are a few interpolation methods to choose from - default is linear. See interp1 help for more info.

Ideas for reducing the complexity of a 3D density function for generating a ternary surface plot in Matlab

I have a 3D density function q(x,y,z) that I am trying to plot in Matlab 8.3.0.532 (R2014a).
The domain of my function starts at a and ends at b, with uniform spacing ds. I want to plot the density on a ternary surface plot, where each dimension in the plot represents the proportion of x,y,z at a given point. For example, if I have a unit of density on the domain at q(1,1,1) and another unit of density on the domain at q(17,17,17), in both cases there is equal proportions of x,y,z and I will therefore have two units of density on my ternary surface plot at coordinates (1/3,1/3,1/3). I have code that works using ternsurf. The problem is that the number of proportion points grows exponentially fast with the size of the domain. At the moment I can only plot a domain of size 10 (in each dimension) with unit spacing (ds = 1). However, I need a much larger domain than this (size 100 in each dimension) and much smaller than unit spacing (ideally as small as 0.1) - this would lead to 100^3 * (1/0.1)^3 points on the grid, which Matlab just cannot handle. Does anyone have any ideas about how to somehow bin the density function by the 3D proportions to reduce the number of points?
My working code with example:
a = 0; % start of domain
b = 10; % end of domain
ds = 1; % spacing
[x, y, z] = ndgrid((a:ds:b)); % generate 3D independent variables
n = size(x);
q = zeros(n); % generate 3D dependent variable with some norm distributed density
for i = 1:n(1)
for j = 1:n(2)
for k = 1:n(2)
q(i,j,k) = exp(-(((x(i,j,k) - 10)^2 + (y(i,j,k) - 10)^2 + (z(i,j,k) - 10)^2) / 20));
end
end
end
Total = x + y + z; % calculate the total of x,y,z at every point in the domain
x = x ./ Total; % find the proportion of x at every point in the domain
y = y ./ Total; % find the proportion of y at every point in the domain
z = z ./ Total; % find the proportion of z at every point in the domain
x(isnan(x)) = 0; % set coordinate (0,0,0) to 0
y(isnan(y)) = 0; % set coordinate (0,0,0) to 0
z(isnan(z)) = 0; % set coordinate (0,0,0) to 0
xP = reshape(x,[1, numel(x)]); % create a vector of the proportions of x
yP = reshape(y,[1, numel(y)]); % create a vector of the proportions of y
zP = reshape(z,[1, numel(z)]); % create a vector of the proportions of z
q = reshape(q,[1, numel(q)]); % create a vector of the dependent variable q
ternsurf(xP, yP, q); % plot the ternary surface of q against proportions
shading(gca, 'interp');
colorbar
view(2)
I believe you meant n(3) in your innermost loop. Here are a few tips:
1) Loose the loops:
q = exp(- ((x - 10).^2 + (y - 10).^2 + (z - 10).^2) / 20);
2) Loose the reshapes:
xP = x(:); yP = y(:); zP = z(:);
3) Check Total once, instead of doing three checks on x,y,z:
Total = x + y + z; % calculate the total of x,y,z at every point in the domain
Total( abs(Total) < eps ) = 1;
x = x ./ Total; % find the proportion of x at every point in the domain
y = y ./ Total; % find the proportion of y at every point in the domain
z = z ./ Total; % find the proportion of z at every point in the domain
PS: I just recognized your name.. it's Jonathan ;)
Discretization method probably depends on use of your plot, maybe it make sense to clarify your question from this point of view.
Overall, you probably struggling with an "Out of memory" error, a couple of relevant tricks are described here http://www.mathworks.nl/help/matlab/matlab_prog/resolving-out-of-memory-errors.html?s_tid=doc_12b?refresh=true#brh72ex-52 . Of course, they work only up to certain size of arrays.
A more generic solution is too save parts of arrays on hard drive, it makes processing slower but it'll work. E.g., you can define several q functions with the scale-specific ngrids (e.g. ngridOrder0=[0:10:100], ngridOrder10=[1:1:9], ngridOrder11=[11:1:19], etc... ), and write an accessor function which will load/save the relevant grid and q function depending on the part of the plot you're looking.

MATLAB - Using for loops find all the combinations of x^2 + y

I have two for loops like this:
for x = 1:1:15
for y = 1:1:15
values(x,y) = x^2 + y
end
end
This allows me to calculate x^2 + y for every combination of x and y if they are integers.
However, what if I want to calculate x^2 + y for decimals as well?
So something like this:
for x = 0:0.1:15
for y = 0:0.1:15
????? = x^2 + y
end
end
Could anyone help me find a method that can calculate all the possibilities of x^2 + y if x and y are decimals so cannot be used as index references anymore?
use meshgrid, matlab's built in rectangular grid in 2-D and there's no need to loop!
[y x]=meshgrid(0:0.1:15)
values=x.^2+y
to visualize this:
imagesc(values);
title('values=x^2+y'); axis square
xlabel('x'); ylabel('y'); colorbar;
axis xy;
set(gca,'XTick',1:10:151,'YTick',1:10:151);
set(gca,'XTickLabel',0:1:15,'YTickLabel',0:1:15);
EDIT:
mdgrid is also fine the only thing to note is that [y x]=meshgrid... is the same [x y]=ndgird...
Use:
[x y] = ndgrid(0:0.1:15);
values = x.^2 + y;
Issues with the other answers:
#inigo's answer will change the order of x and y compared to your initial example (by using meshgrid rather than ndgrid.
#NominSim's answer has to go to extra effort get d_x from x
#mecid's answer has to count columns and rows separately (also there is no ++ operator in MATLAB). If I was to go down #mecid's route I would use the following.
x = 0:.1:15;
y = 0:.1:15;
values = zeros(numel(x),numel(y));
for xnum = 1:numel(x)
for ynum = 1:numel(y)
values(xnum,ynum) = x(xnum)^2 + y(ynum);
end
end
Since it generated some discussion, from the documentation (within MATLAB, not in the online documentation) on the difference between meshgrid and ndgrid:
meshgrid is like ndgrid except that the order of the first two input and output arguments are switched (i.e., [X,Y,Z] = meshgrid(x,y,z) produces the same result as [Y,X,Z] = ndgrid(y,x,z)) ... meshgrid is also limited to 2D or 3D.
for x =1:0.1:15
for y=1:0.1:15
values(x*10-10, y*10-10) =x^2+y;
end
end
Why not loop on integers from 1 to 151 then calculate the decimal to be used? Then you can still use index references.
i.e.
for x = 1:1:151
for y = 1:1:151
d_x = x / 10.0 - 0.1
d_y = y / 10.0 - 0.1
values(x,y) = d_x^2 + d_y
end
end
(Forgive me if my syntax is slightly off, haven't used MATLAB in a while).