I would like to develop some intuition for this language. Specifically about plotting functions on some interval. Here is a concrete example I am trying to work out. Plot exp(x) over the closed interval [-2,2]. Here exp(x) is Matlab notation for e^x, I think. This is the script based on a guide I just read :
x = [ -2 , 2 ];
y = exp(x);
plot(x,y)
The result is not an exponential curve, but a straight line. What is wrong with this script? And also, if anyone can recommend a good guide for this, I would appreciate it very much. Google results I found only have worked examples.
Two methods of adjusting the number of points plotted (samples) of the function are to either specify the interval between the points or the number of points to be plotted. The plot() function will plot the vectors x and y which will plot the number of points equal to the length of vector x. Similar idea to an Excel sheet scatter plot that is joined with line.
Setting the Interval Between the Plotting Points
X_Minimum = -2;
X_Maximum = 2;
Plotting_Interval = 0.25;
x = (X_Minimum: Plotting_Interval: X_Maximum);
y = exp(x);
plot(x,y,'o-');
title(num2str(Plotting_Interval) + " Interval Between Points");
Setting the Number of Plotting Points
X_Minimum = -2;
X_Maximum = 2;
Number_Of_Points = 18;
x = linspace(X_Minimum,X_Maximum,Number_Of_Points);
y = exp(x);
plot(x,y,'o-');
title(num2str(Number_Of_Points) + " Points Plotted");
Ran using MATLAB R2019b
This is because you only input two point into the function plot():(-2,exp(-2)),(2,exp(2))
.In matlab,the x &y of plot(x,y) are vector of the points you have but not their intervals.
I have the following code
x = linspace(-pi, pi, 1e3);
y = sqrt((x).^(1/2));
plot(x, real(y));
plot(x, imag(y));
The value at x=-1 on the real and imaginary plots are both 0.7071 (sqrt(0.5). Why is it not 0 (real) and 1 (imaginary)? When I enter this code:
real((-1)^(1/2))
imag((-1)^(1/2))
this gives me 0 (real) and 1 (imaginary) as expected.
Any help would be much appreciated.
Thanks,
Note that sqrt((x).^(1/2)) = x.^(1/4)
This is not all imaginary since (-i)^4 = i^4 = -1*-1 = 1. Consider what happens on the complex plane and you should be able to arrive at the conclusion that if y^4 = -1 then y = exp(i*(2*N-1)*pi/4) where N is any integer.
This leads to 4 unique solutions for y which are +/-sqrt(2)/2 +/- i*sqrt(2)/2. MATLAB returns the one where both real and imaginary are positive.
I want to write a script to generate a 3D vector field of the electric flux density of 8 different point charges in a [-2,2]x[-2,2]x[-2,2] box in 3D space.
I have a function definition in a separate .m file as follows:
function[Dx,Dy,Dz]= question3function(Q,Loc,XX,YY,ZZ)
Q=1e-6;
Loc=[];
XX=(2,-2);
YY=[2,-2];
ZZ=[2,-2];
% Position vector from the point charge
Rx=(XX)-Loc([]);
Ry=(YY)-Loc([]);
Rz=(ZZ)-Loc([]);
% Distance between position in interest and the point charge
R=sqrt(Rx.*Rx+Ry.*Ry+Rz.*Rz);
% Unit Position vector
Ax=Rx./R;
Ay=Ry./R;
Az=Rz./R;
% Electric flux density XYZ components
K=Q./(4*pi*R.^2);
Dx=K.*Ax;
Dy=K.*Ay;
Dz=K.*Az;
And then in my main script I have the function calls:
%function calls
[Dx1,Dy1,Dz1]=question3function(Q,[1 1 1],XX,YY,ZZ);
[Dx2,Dy2,Dz2]=question3function(Q,[1 1 -1],XX,YY,ZZ);
[Dx3,Dy3,Dz3]=question3function(Q,[1 -1 1],XX,YY,ZZ);
[Dx4,Dy4,Dz4]=question3function(-Q,[1 -1 -1],XX,YY,ZZ);
[Dx5,Dy5,Dz5]=question3function(2*Q,[-1 1 1],XX,YY,ZZ);
[Dx6,Dy6,Dz6]=question3function(-2*Q,[-1 1 -1],XX,YY,ZZ);
[Dx7,Dy7,Dz7]=question3function(-Q,[-1 -1 1],XX,YY,ZZ);
[Dx8,Dy8,Dz8]=question3function(-Q,[-1 -1 1],XX,YY,ZZ);
Dx=Dx1+Dx2+Dx3+Dx4+Dx5+Dx6+Dx7+Dx8;
Dy=Dy1+Dy2+Dy3+Dy4+Dy5+Dy6+Dy7+Dy8;
Dz=Dz1+Dz2+Dz3+Dz4+Dz5+Dz6+Dz7+Dz8;
quiver3(XX,YY,ZZ,Dx,Dy,Dz);
axis square equal;
xlabel('X'); ylabel('Y'); zlabel('Z');
title('Electric Flux Density of the sum of 8 Point Charges');
I receive the following errors when I try to run my function file:
??? Error using ==> minus
Matrix dimensions must agree.
Error in ==> question3function at 11
Rx=(XX)-Loc([]);
Could somebody please help me and explain how I can fix this? I will add I am not very experienced with using MATLAB.
There are a number of meaningless things that you are doing here:
function[Dx,Dy,Dz]= question3function(Q,Loc,XX,YY,ZZ)
Q=1e-6; % this is meaningless
Loc=[]; % this is meaningless
XX=(2,-2); % this is meaningless ()
YY=[2,-2]; % this is meaningless
ZZ=[2,-2]; % this is meaningless
% Position vector from the point charge
Rx=(XX)-Loc([]); % this is meaningless ([])
Ry=(YY)-Loc([]); % this is meaningless ([])
Rz=(ZZ)-Loc([]); % this is meaningless ([])
% Distance between position in interest and the point charge
R=sqrt(Rx.*Rx+Ry.*Ry+Rz.*Rz);
% Unit Position vector
Ax=Rx./R;
Ay=Ry./R;
Az=Rz./R;
% above why do you need all of them to be unit vectors
% you can
% Electric flux density XYZ components
K=Q./(4*pi*R.^2);
Dx=K.*Ax;
Dy=K.*Ay;
Dz=K.*Az;
Moreover, in %function calls how are defining XX, YY and ZZ?
The second half of your function declaration is sound, but you're missing the point of how functions work. The point of function parameters is that the function uses those variables as input. Assigning to input parameters is usually a semantic error: it's generally not what you want to do. Another problem is that in matlab vectors are defined with square brackets, and frankly (2,-2) should give you an error about unbalanced parentheses... Always make sure to check your code before posting a question about it on Stack Overflow: if you change it before posting, you might have inadvertently removed your original problem.
You can use your original function by removing the superfluous variable redefinitions at the beginning, and by fixing the assignment to Rx/Ry/Rz. When you say Loc([]), you are indexing with an empty vector, and the result is an empty variable. This is obviously not what you need. Instead:
function [Dx,Dy,Dz]=question3function(Q,Loc,XX,YY,ZZ)
%Q, Loc, XX, ZZ, YY: input!
% Position vector from the point charge
Rx = XX - Loc(1); %use first component of Loc for every x
Ry = YY - Loc(2); %use second component of Loc for every y
Rz = ZZ - Loc(3); %use third component of Loc for every z
% Distance between position in interest and the point charge
R=sqrt(Rx.^2+Ry.^2+Rz.^2); % .^2 takes less characters
% Unit Position vector
Ax=Rx./R;
Ay=Ry./R;
Az=Rz./R;
% Electric flux density XYZ components
K=Q./(4*pi*R.^2);
Dx=K.*Ax;
Dy=K.*Ay;
Dz=K.*Az;
Then you should define XX, YY, ZZ, Q and Loc in your calling function/script. Also, if you're only interested in the total flux density, you could spare some keyboard-time by defining every charge and their location in arrays, and calling your function in a loop:
%define mesh
N = 5; % number of points for mesh in each dimension
[XX,YY,ZZ] = meshgrid(linspace(-2,2,N));
%define charges and locations in arrays
Q0 = 1e-6;
Qvec = Q0*[1 1 1 -1 2 -2 -1 -1];
Locmat = [1 1 1; 1 1 -1; 1 -1 1; 1 -1 -1;...
-1 1 1; -1 1 -1; -1 -1 1; -1 -1 1]; % last 2 are duplicates!!
%function calls in loop, keep adding up flux components
Dx=zeros(size(XX));
Dy=zeros(size(XX));
Dz=zeros(size(XX));
for k=1:length(Qvec)
Q = Qvec(k);
Loc = Locmat(k,:);
[Dxtmp, Dytmp, Dztmp] = question3function(Q,Loc,XX,YY,ZZ);
Dx = Dx + Dxtmp;
Dy = Dy + Dytmp;
Dz = Dz + Dztmp;
end
%plot, no changes here
quiver3(XX,YY,ZZ,Dx,Dy,Dz);
axis square equal;
xlabel('X'); ylabel('Y'); zlabel('Z');
title('Electric Flux Density of the sum of 8 Point Charges');
Output:
I have two datasets, one of which is a target position, and the other is the actual position. I would like to plot the target with a +/- acceptable range and then overlay with the actual. This question is only concerning the target position however.
I have unsuccessfully attempted the built in area, fill, and rectangle functions. Using code found on stackoverflow here, it is only correct in certain areas.
For example
y = [1 1 1 2 1 1 3 3 1 1 1 1 1 1 1]; % Target datum
y1 = y+1; %variation in target size
y2 = y-1;
t = 1:15;
X=[t,fliplr(t)]; %create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %create y values for out and then back
fill(X,Y,'b');
The figure produced looks like this:
I would prefer it to be filled within the red boxes drawn on here:
Thank you!
If you would just plot a function y against x, then you could use a stairs plot. Luckily for us, you can use the stairs function like:
[xs,ys] = stairs(x,y);
to create the vectors xs, ys which generate a stairs-plot when using the plot function. We can now use these vectors to generate the correct X and Y vectors for the fill function. Note that stairs generates column vectors, so we have to transpose them first:
y = [1 1 1 2 1 1 3 3 1 1 1 1 1 1 1]; % Target datum
y1 = y+1; %variation in target size
y2 = y-1;
t = 1:15;
[ts,ys1] = stairs(t,y1);
[ts,ys2] = stairs(t,y2);
X=[ts.',fliplr(ts.')]; %create continuous x value array for plotting
Y=[ys1.',fliplr(ys2.')]; %create y values for out and then back
fill(X,Y,'b');
Again, thank you hbaderts. You answered my question perfectly, however when I applied it to the large data set I needed for, I obtained this image
https://dl.dropboxusercontent.com/u/37982601/stair%20fill.png
I think it is because the fill function connects vertices to fill?
In any case, for the potential solution of another individual, combined your suggested code with the stair function and used the area function.
By plotting them on top of one another and setting the color of the lower area to be white, it appears as the rectangular figures I was after.
%sample code. produces image similar to o.p.
y = [1 1 1 2 1 1 3 3 1 1 1 1 1 1 1];
y1 = y+1;
y2 = y-1;
t = 1:15;
[ts,ys1] = stairs(t,y1);
[ts,ys2] = stairs(t,y2);
area(ts,ys1,'FaceColor','b','EdgeColor','none')
hold on
area(ts,ys2,'FaceColor','w','EdgeColor','none')
https://dl.dropboxusercontent.com/u/37982601/stair%20area.png
Thanks again for your help and for pointing me in the right direction!
I am using Matlab to find the spectral radius of the Jacobi iteration matrix where A=[4 2 1;1 3 1;1 1 4].
I can't seem to input the correct commands to get the size of the error after 5 iterations. Can someone help me?
Here are a list of commands that I put into Matlab so far:
A=[4 2 1;1 3 1;1 1 4]
A =
4 2 1
1 3 1
1 1 4
D=diagonal(diagonal(A));L=(A,-1);U=(A,1);
b=([3 -1 4])
x0j=zeros([0 0 0]);
x=D\(-(U+L)*x0j+b);r=b-A*x %Jacobi iteration.
------------------------------------------------------------------------------
Error using *
Inputs must be 2-D, o enter code here r at least one input must be scalar.
To compute element wise TIMES, use TIMES (.*) instead.
The spectral radius of a matrix is the maximum of the modulus of its eigenvalues. It can be simply computed using max(abs(eig(·))).
However, as others have noticed, your whole code seems pretty mixed up and not actually valid Matlab code, so your problem is not really to compute the spectral radius, is it? The algorithm is very straightforward and easy to implement:
% diagonal part of A and rest
D = diag(diag(A));
R = A - D;
% iteration matrix and offset
T = - inv(D) * R;
C = inv(D) * b;
% spectral radius condition
rho = max(abs(eig(T)));
if rho >= 1
error('no convergence')
end
% initial guess
x = randn(size(b));
% iteration
while norm(A * x - b) > 1e-15
x = T * x + C;
end
Note that I used inv(D) to directly follow the description in Wikipedia, but the inverse of a diagonal matrix can be easily computed using diag(1 ./ diag(D)).
I don't really see why one would need to separate R into an upper and lower part. I suppose it has to do with numerical efficiency, but then, Matlab is a very efficient high-level language for matrix computations already. So actually there is no need to implement the Jacobi algorithm in it explicitly when you can simply write A \ b – except for educational purposes I guess.