Plotting complex functions in matlab - matlab

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.

Related

Plotting an exponential function in matlab

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.

Is there an optimized vectorized function of the rectified linear function max(0,x) in MATLAB?

I was trying to get an vector optimized version of the linear rectifier. i.e. y = max(0,x). So what it should compute its element wise max of zero and x_i. I obviously implemented:
function [ y ] = rectSig( x )
%rectSig computes vector-wise rectified linear function
% computes y = [..., max(0,x_i), ...]
n=length(x);
y = zeros(1,n);
for i=1:1:length(x);
y(i) = max(0,x(i));
end
end
however, I know that looping like this in MATLAB is ill advised. So I was wondering if there was a better way to do this or if obviously matlab had its own implementation of a vectorized version of such a function? I always try to avoid loops if I can in matlab if there is a way to vectorize my code. It usually tends to speed things up.
Btw, I obviously tried googling it but didn't really get the result I expected...
The solution is as simple as
y = max(x,0);
This works for x being a column, row vector, matrix, higher dimensional matrix, etc. On the other hand
y = max(zeros(1,length(x)),x);
only works for x being a row vector. It fails when x is a column vector or matrix.
max accepts matrix inputs:
x = -5:5;
comparisonvector = zeros(size(x));
y = max(comparisonvector, x);
Returns:
y =
0 0 0 0 0 0 1 2 3 4 5

MATLAB 'Error using plot Vectors must be the same length.'

x = 0:1:5; % define x array
y = exp(x)+x.^4+2*x.^2-x+3; % define y array
dx = diff(x); % 1 1 1 1 1 dx has one number less than x
dy = diff(y); % -5 -1 -3 -4 -2
slope = dy./dx
z=exp(x)+4*x.^3 +4*x-1
plot(x,slope,'*',x,z)
'Error using plot Vectors must be the same length.'
Been stuck on this for a while, I am not sure what to do. ive seen the other responses to the same error but can not understand the code. It seems its the colon : that might help but i am not sure how to use it.
Any help would be appreciated!
Since slope is computed from two consecutive values, I suggest you take the average betwen consecutive points as the x-axis values for ´slope`:
plot((x(1:end-1)+x(2:end))/2,slope, '*',x,z)

Scale Space for solving Sum of Gaussians

I'm attempting to use scale space implementation to fit n Gaussian curves to peaks in a noisy time series digital signal (measuring voltage).
To test it I created the following sample sum of three gaussians with noise (0.2*rand, sorry no picture, i'm new here)
amp = [2; 0.9; 1.3];
mu = [19; 23; 28];
sigma = [4.8; 1.3; 2.5];
x = linspace(1,50,1000);
for n=1:3, y(n,:) = A(n)*exp(-(x-B(n)).^2./(2*C(n)^2)); end
noisysignal = y(1,:) + y(2,:) + y(3,:) + 0.2*rand(1,numel(x))
I found this article http://www.engineering.wright.edu/~agoshtas/GMIP94.pdf posted by user355856 answer to thread "Peak decomposition"!
I believe my code generates the correct result for plotting the zero crossings as a function of the gaussian filter resolution sigma, but I have two issues. The first is that it seems yet another fitting routine would be needed to identify the approximate location of the arch intercepts for approximating the initial peak sigma and mu values. The second is that the edges of the scale space plot have substantial arches that definitely do not correspond to any peak. I'm not sure how to screen these out effectively. Last thing is that is used a spacing of 50 when calculating the second derivative central finite difference since too much more destroyed feature, and to much less results in a forest of zero crossings. Would there be a better way to filter that to control random zero crossings in the gaussian peak tails?
function [crossing] = scalespace(x, y, sigmalimit)
figure; hold on; ylim([0 sigmalimit]);
for sigma = 1:sigmalimit %
yconv = convkernel(sigma, y); %convolve with kernel
xconv = linspace(x(1), x(end), length(yconv));
yconvpp = d2centralfinite(xconv, yconv, 50); % 50 was empirically chosen
num = 0;
for i = 1 : length(yconvpp)-1
if sign(yconvpp(i)) ~= sign(yconvpp(i+1))
crossing(sigma, num+1) = xconv(i);
num = num+1;
end
end
plot(crossing(sigma, crossing(sigma, :) ~= 0),...
sigma*ones(1, numel(crossing(sigma, crossing(sigma, :) ~= 0))), '.');
end
function [yconv] = convkernel(sigma, y)
t = sigma^2;
C = 3; % for kernel truncation
M = C*round(sqrt(t))+1;
window = (-M) : (+M);
G = zeros(1, length(window));
G(:) = (1/(2*pi()*t))*exp(-(window.^2)./(2*t));
yconv = conv(G, y);
This is my first post and I apologize in advance for any issues in style. I'm fairly new to programming, so any advice regarding the programming style or information provided in this question would be much appreciated. I also read through Amro's answer about matlab's GMM function! if anyone feels that would be a more efficient approach to modeling multiple gaussians in a digital signal.
Thank you!

Trapz giving weird results

I'm having a weird result with Matlab's trapz function. I have two variables, zptest and omega, both of which are positive, 3000x2x1 arrays.
When I plot zptest vs omega (plot(zptest(:,1,1),omega(:,1,1)) the curve is clearly positive and should give a positive result when integrating. This is not the case, however, as shown below:
trapz(zptest(:,1,1),omega(:,1,1))
ans =
-0.049999940237341
just to prove that both omega and zptest are positive:
find(omega(:,1,1) < 0)
ans =
Empty matrix: 0-by-1
find(zptest(:,1,1) < 0)
ans =
Empty matrix: 0-by-1
I know I'm not giving any context to what I'm actually doing but this seems like a context independent problem. Does anyone have any idea what's going on?
Try re-ordering x in ascending order (and y-values accordingly):
x_order = x(end:-1:1); %fliplr
y_order = y(end:-1:1); %fliplr
trapz(x_order, y_order)
In trapz(x,y) differentiation of x is applied through diff(x,1,1), i.e. [x(2:n,:) - x(1:n-1,:)]. If your x is descending this will give negative dx. It doesn't matter if it is positive or negative. However, in plot the curve will appear positive-definite (you don't actually see the order of points, just pairs from two vectors on a plane).
Example (compare the following):
x = [-1 -0.5 0]; y = 0.5-x;
figure; plot(x,y); hold on; plot(-x, y,'r')
trapz(x, y)
trapz(-x, y)
figure; plot(x, y); hold on; plot(fliplr(-x), fliplr(y),'r')
trapz(fliplr(-x), fliplr(y))
Think of it like this. The integral of a function that is always positive, if the limits are inverted, will still be negative. Thus we know that
int(x^2,-1,1) = 2/3
But
int(x^2,1,-1) = -2/3
Clearly x.^2 is always a positive number, but here the limits of integration were not increasing, but decreasing.
If the x_i in the call to trapz are not in increasing order, then you will get negative results. This is reflected by trapz. Trapz sees the order of the points as presented to it.
x = -1:.1:1;
trapz(x,x.^2)
ans =
0.67
xrev = fliplr(x);
trapz(xrev,xrev.^2)
ans =
-0.67
And, as pointed out by gevang, the plot shows only that the function is positive, not the order of the points.