Matlab Specifying Variable Continous Range in Equation - matlab

I am trying to get solutions of a equation and then plot the result on a graph in MATLAB. Suppose, if a equation is,
R=A*sin(theta)
Where, A is a variable, say from 0 to 5 (which will be plotted on x-axis) and theta is from 0 to 3. The resultant values of R, for continous range of A i.e. 0 to 5, will be plotted on y-axis.
I would like to ask that, in MATLAB, how can I get a continous range of variable A, (and that of theta as well), so that I can plot the values on a graph with respective continous-values (or resultant values) of R?

you can use ezplot(fun, [xmin xmax]):
theta = pi;
R =#(A) A*sin(theta);
ezplot(R,[0 5]);
EDIT:
In case you want theta range as well you can use the 3D equivalent: ezsurf or fsurf(fun, [xmin xmax ymin ymax]), like that:
R = #(theta,A) A*sin(theta);
ARange = [0 5];
thetaRange = [0 3];
fsurf(R,[thetaRange ARange]);
xlabel('\theta')
ylabel('A')
title('A\cdotsin(\theta)')

Related

Draw a line with non-Cartesian coordinates in MATLAB

MATLAB's surf command allows you to pass it optional X and Y data that specify non-cartesian x-y components. (they essentially change the basis vectors). I desire to pass similar arguments to a function that will draw a line.
How do I plot a line using a non-cartesian coordinate system?
My apologies if my terminology is a little off. This still might technically be a cartesian space but it wouldn't be square in the sense that one unit in the x-direction is orthogonal to one unit in the y-direction. If you can correct my terminology, I would really appreciate it!
EDIT:
Below better demonstrates what I mean:
The commands:
datA=1:10;
datB=1:10;
X=cosd(8*datA)'*datB;
Y=datA'*log10(datB*3);
Z=ones(size(datA'))*cosd(datB);
XX=X./(1+Z);
YY=Y./(1+Z);
surf(XX,YY,eye(10)); view([0 0 1])
produces the following graph:
Here, the X and Y dimensions are not orthogonal nor equi-spaced. One unit in x could correspond to 5 cm in the x direction but the next one unit in x could correspond to 2 cm in the x direction + 1 cm in the y direction. I desire to replicate this functionality but drawing a line instead of a surf For instance, I'm looking for a function where:
straightLine=[(1:10)' (1:10)'];
my_line(XX,YY,straightLine(:,1),straightLine(:,2))
would produce a line that traced the red squares on the surf graph.
I'm still not certain of what your input data are about, and what you want to plot. However, from how you want to plot it, I can help.
When you call
surf(XX,YY,eye(10)); view([0 0 1]);
and want to get only the "red parts", i.e. the maxima of the function, you are essentially selecting a subset of the XX, YY matrices using the diagonal matrix as indicator. So you could select those points manually, and use plot to plot them as a line:
Xplot = diag(XX);
Yplot = diag(YY);
plot(Xplot,Yplot,'r.-');
The call to diag(XX) will take the diagonal elements of the matrix XX, which is exactly where you'll get the red patches when you use surf with the z data according to eye().
Result:
Also, if you're just trying to do what your example states, then there's no need to use matrices just to take out the diagonal eventually. Here's the same result, using elementwise operations on your input vectors:
datA = 1:10;
datB = 1:10;
X2 = cosd(8*datA).*datB;
Y2 = datA.*log10(datB*3);
Z2 = cosd(datB);
XX2 = X2./(1+Z2);
YY2 = Y2./(1+Z2);
plot(Xplot,Yplot,'rs-',XX2,YY2,'bo--','linewidth',2,'markersize',10);
legend('original','vector')
Result:
Matlab has many built-in function to assist you.
In 2D the easiest way to do this is polar that allows you to make a graph using theta and rho vectors:
theta = linspace(0,2*pi,100);
r = sin(2*theta);
figure(1)
polar(theta, r), grid on
So, you would get this.
There also is pol2cart function that would convert your data into x and y format:
[x,y] = pol2cart(theta,r);
figure(2)
plot(x, y), grid on
This would look slightly different
Then, if we extend this to 3D, you are only left with plot3. So, If you have data like:
theta = linspace(0,10*pi,500);
r = ones(size(theta));
z = linspace(-10,10,500);
you need to use pol2cart with 3 arguments to produce this:
[x,y,z] = pol2cart(theta,r,z);
figure(3)
plot3(x,y,z),grid on
Finally, if you have spherical data, you have sph2cart:
theta = linspace(0,2*pi,100);
phi = linspace(-pi/2,pi/2,100);
rho = sin(2*theta - phi);
[x,y,z] = sph2cart(theta, phi, rho);
figure(4)
plot3(x,y,z),grid on
view([-150 70])
That would look this way

Dom::Interval function in Matlab Error

I am trying to plot f(x)=sin(x) in Matlab, but am having trouble defining my variable x as the interval [0,pi/2]. I have:
x1 = Dom::Interval([0], [1])
y1 = cos(x1)
plot(x1,y1)
However, the interval function in Matlab returns as an unexpected Matlab operator.
Dom::Interval is part of the MuPad interface. Simply create a numeric array from 0 to pi/2 and plot the sin of the result.
x1 = linspace(0, pi/2);
y1 = sin(x);
plot(x1, y1);
linspace generates a numeric array with a default amount of 100 points linearly spaced from 0 to pi/2. You can override the amount of points by specifying a third element... something like:
x1 = linspace(0, pi/2, 300);
This creates 300 points. Play around with the third parameter. The more points you have, the more smooth the plot will be as the default method of plotting things in MATLAB is to just join the points together with straight lines.

drawing 3d contour plot from 3d vector

I want to draw a contour plot for 3D data.
I have a force in x,y,z directions I want to plot the contour3 for that
the dimensions of the Fx = 21x21X21 same for Fy and Fz
I am finding force = f*vector(x,y,z)
Then
Fx(x,y,z) = force(1)
Fy(x,y,z) = force(2)
Fz(x,y,z) = force(3)
I did the following but it is not working with me ?? why and how can I plot that
FS = sqrt(Fx.^2 + Fy.^2 + Fz.^2);
x = -10:1:10;
[X,Y] = meshgrid(x);
for i=1:length(FS)
for j = 1:length(FS)
for k=1:length(FS)
contour3(X,Y,FS(i,j,k),10)
hold on
end
end
end
This is the error I am getting
Error using contour3 (line 129)
When Z is a vector, X and Y must also be vectors.
Your problem is that FS is not the same shape as X and Y.
Lets illustrate with a simple example:
X=[1 1 1
2 2 2
3 3 3];
Y=[1 2 3
1 2 3
1 2 3];
Z=[ 2 4 5 1 2 5 5 1 2];
Your data is probably something like this. How does Matlab knows which Z entry corresponds to which X,Y position? He doesnt, and thats why he tells you When Z is a vector, X and Y must also be vectors.
You could solve this by doing reshape(FS,size(X,1),size(X,2)) and will probably work in your case, but you need to be careful. In your example, X and Y don't seem programatically related to FS in any way. To have a meaningful contour plot, you need to make sure that FS(ii,jj,k)[ 1 ] corresponds to X(ii,jj), else your contour plot would not make sense.
Generally you'd want to plot the result of FS against the variables your are using to compute it, such as ii, jj or k, however, I dont know how these look like so I will stop my explanation here.
[ 1 ]: DO NOT CALL VARIABLES i and j IN MATLAB!
I'm not sure if this solution is what you want.
Your problem is that contour and contour3 are plots to represent scalar field in 2D objects. Note that ball is 2D object - every single point is defined by angles theta and phi - even it is an object in "space" not in "plane".
For representation of vector fields there is quiver, quiver3, streamslice and streamline functions.
If you want to use contour plot, you have to transform your data from vector field to scalar field. So your data in form F = f(x,y,z) must be transformed to form of H = f(x,y). In that case H is MxN matrix, x and y are Mx1 and Nx1 vectors, respectively. Then contour3(x,y,H) will work resulting in so-called 3D graph.
If you rely on vector field You have to specify 6 vectors/matrices of the same size of corresponding x, y, z coordinates and Fx, Fy, Fz vector values.
In that case quiver3(x,y,z,Fx,Fy,Fz) will work resulting in 6D graph. Use it wisely!
As I comment the Ander's answer, you can use colourspace to get more dimensions, so You can create 5D or, theoretically, 6D, because you have x, y, z coordinates for position and R, G, B coordinates for the values. I'd recommend using static (x,y,R,G,B) for 5D graph and animated (x,y,t,R,G,B) for 6D. Use it wisely!
In the example I show all approaches mentioned above. i chose gravity field and calculate the plane 0.25 units below the centre of gravity.
Assume a force field defined in polar coordinates as F=-r/r^3; F=1/r^2.
Here both x and yare in range of -1;1 and same size N.
F is the MxMx3 matrix where F(ii,jj) is force vector corresponding to x(ii) and y(jj).
Matrix H(ii,jj) is the norm of F(ii,jj) and X, Y and Z are matrices of coordinates.
Last command ensures that F values are in (-1;1) range. The F./2+0.5 moves values of F so they fit into RGB range. The colour meaning will be:
black for (-1,-1,-1),
red for (1,-1,-1),
grey for (0,0,0)
Un-comment the type of plot You want to see. For quiver use resolution of 0.1, for other cases use 0.01.
clear all,close all
% Definition of coordinates
resolution=0.1;
x=-1:resolution:1;
y=x;
z=-.25;
%definition of matrices
F=zeros([max(size(x))*[1 1],3]); % matrix of the force
X=zeros(max(size(x))*[1 1]); % X coordinates for quiver3
Y=X; % Y coordinates for quiver3
Z=X+z; % Z coordinates for quiver3
% Force F in polar coordinates
% F=-1/r^2
% spherical -> cartesian transformation
for ii=1:max(size(x))
for jj=1:max(size(y))
% temporary variables for transformations
xyz=sqrt(x(ii)^2+y(jj)^2+z^2);
xy= sqrt(x(ii)^2+y(jj)^2);
sinarc=sin(acos(z/xyz));
%filling the quiver3 matrices
X(ii,jj)=x(ii);
Y(ii,jj)=y(jj);
F(ii,jj,3)=-z/xyz^2;
if xy~=0 % 0/0 error for x=y=0
F(ii,jj,2)=-y(jj)/xyz/xy*sinarc;
F(ii,jj,1)=-x(ii)/xyz/xy*sinarc;
end
H(ii,jj)=sqrt(F(ii,jj,1)^2+F(ii,jj,2)^2+F(ii,jj,3)^2);
end
end
F=F./max(max(max(F)));
% quiver3(X,Y,Z,F(:,:,1),F(:,:,2),F(:,:,3));
% image(x,y,F./2+0.5),set(gca,'ydir','normal');
% surf(x,y,Z,F./2+.5,'linestyle','none')
% surf(x,y,H,'linestyle','none')
surfc(x,y,H,'linestyle','none')
% contour3(x,y,H,15)

Matlab 3D Plot of transfer function magnitude

How can I plot amplitude of transfer function in three dimension (for instance to check poles and zeros on graph) ?
Suppose this is my transfer function:
My code:
b = [6 -10 2];
a = [1 -3 2];
[x, y] = meshgrid(-3:0.1:3);
z = x+y*j;
res = (polyval(b, z))./(polyval(a,z));
surf(x,y, abs(res));
Is it correct? I'd also like to know is it possible to mark unit circle on plot?
I think it's correct. However, you're computing H(z^-1), not H(z). Is that you want to do? For H(z), just reverse the entries in a from left to right (with fliplr), and do the same to b:
res = (polyval(fliplr(b), z))./(polyval(fliplr(a),z));
To plot the unit circle you can use rectangle. Seriously :-) It has a 'Curvature' property which can be set to generate a circle.
It's best if you use imagesc instead of surf to make the circle clearly visible. You will get a view from above, where color represents height (value of abs(H)):
imagesc(-3:0.1:3,-3:0.1:3, abs(res));
hold on
rectangle('curvature', [1 1], 'position', [-1 -1 2 2], 'edgecolor', 'w');
axis equal
I have never in my whole life heard of a 3D transfer function, it doesn't make sense. I think you are completely wrong: z does not represent a complex number, but the fact that your transfer function is a discrete one, rather than a continuous one (see the Z transform for more details).
The correct way to do this in MATLAB is to use the tf function, which requires the Control System Toolbox (note that I have assumed your discrete sample time to be 0.1s, adjust as required):
>> b = [6 -10 2];
a = [1 -3 2];
>> sys = tf(b,a,0.1,'variable','z^-1')
sys =
6 - 10 z^-1 + 2 z^-2
--------------------
1 - 3 z^-1 + 2 z^-2
Sample time: 0.1 seconds
Discrete-time transfer function.
To plot the transfer function, use the bode or bodeplot function:
bode(sys)
For the poles and zeros, simply use the pole and zero functions.

MATLAB: How do I graph multiple functions on the same graph?

How can I graph multiple functions on the same graph/plot/Cartesian plane on MATLAB with domain and range restrictions?
For example I made up the following functions below. How would I graph the following on the same graph within MATLAB?
Function 1: x = -3 for 10 <= y <= 14
Function 2: y = -2x for -5 <= x <= -4
Function 3: (x-0)^2 + (y-12)^2 = 2.25 // Produces a circle
Function 4: y = 4 for -1 <= x <= 1
Matlab is a numerical computing environment, so you'll need to tell it what you're looking for while plotting.
In the case of your first example, you'll need to tell it which Y values to plot. Since X is always the same, you know it's going to be a line - so two points will be enough. Plot requires parallel arrays, so:
Function 1: x = [-3 -3]; y = [10 14]; plot(x, y);
To plot additional lines on the same graph, use the command hold on, which applies to the figure you just plotted. If you don't do this, new plot commands will erase the old plots.
Similarly,
Function 2: x = [-5 4]; y = -2*x; plot(x, y);
For circles/ellipses like #3, ezplot can be helpful, although you still have to specify the range.
Function 3: ezplot('x^2 + (y-12)^2 - 2.25', [-3,3,10,14])
The last one is easy, but let's say it were a curve instead. You'd want to plot more than just two x values. You can create a vector from a range like this: x = -1:0.1:1;, or an evenly space set of points from -1 to 1, with an interval of 0.1. Let's say you want to plot it on the same graph, and you've already done hold on. You want a different color, and you want to show the individual points that make up the line, you can use the third argument to the plot function:
Function 4: x = -1:0.1:1; y = 4 * ones(length(x)); plot(x, y, '-r.');
The second command here, y = 4 * ones(length(x)); simply creates a y vector that is the same length as x.