Matlab function won't plot - matlab

Trying to plot a function on matlab, however the graph comes out completely empty
X = linspace(-2,2);
Y = (10*exp(X./10) - 7)/(exp(X.*(33/10)));
plot(X,Y);

You need to use element-wise operation for division:
Y = (10*exp(X./10) - 7)./(exp(X.*(33/10)));
Plotting will work fine then. The problem now is that Y is a one-element array.
I want to add here that, the only operation that should be element-wise operation is the division in the middle. The other operations don't need the '.' as the division of array by scalar as no other meaning. So, it should better be written like this:
Y = (10*exp(X/10) - 7)./(exp(X*(33/10)));

Just a few points to add on to #hesham_EE's excellent answer:
For beginners, it's best to only use * when you are doing matrix multiplication. For arithmetic and/or element-wise operations, stick with .*
It is helpful in debugging to print the output of each row of computation, i.e. omit the semicolon. This allows you to check your syntax. In this case, you would have noticed that Y was not what you had intended it to be.

Related

Rewrite summation formula to MatLab

I have a following formula:
and I need it to rewrite it to MatLab. The problem is, I'm not very experienced with it, so I'm not sure, if this is the right way to do it.
My code looks like this:
f = #(alpha, beta, gamma, delta)...
alpha*sum((DOF.^(2*beta)) .* log(DOF))...
+ gamma*sum( (DOF.^(beta+delta) .* log(DOF))./nprocs )
DOF and nprocs are vectors of numbers with n elements.
Is it ok or is there some mistake in my code? I'm not sure about the summation of i-th members especially, I'm quite confused by those vector multiplications etc.
Your code looks good.
You do not need .^ - you can just use ^,
assuming beta,delta etc are scalar.
I should mention that the variable DOF and nprocs may be treated as a "closure" - i.e. will be incorporated from the scope in which the function is defined. If you want to avoid this, DOF and nprocs should be included as a parameter.

Can I avoid the for loop in normalizing data by using : operator in matlab?

Here is the code I am using -
mu = mean(X);
sigma = std(X);
for iter = 1:size(X, 1)
X_norm(iter,:)=((X(iter,:)-mu)./sigma)
end
I was wondering if there was a way to do this without using a loop and using only the basic operators, something by which I could add each row in X by mu and divide each by sigma.
X and X_norm are matrices.
One way I found out is - (Although it uses the function ones )
one= ones(size(X, 1), 1);
X_norm = (X - one*(mean(X)))./(one*std(X));
Please note that I want to know more about using the basic operators so don't suggest any libraries or toolkits .
If you are going to post a function, post its implementation as well
Use bsxfun -
X_norm = bsxfun(#rdivide,bsxfun(#minus,X,mu),sigma)
You can also use ones() with your beloved operator : for replication as stated in Loren's blog and then perform the stated operations, like so -
M = size(X,1);
X_norm = (X - mu(ones(M,1),:))./sigma(ones(M,1),:)
For performance, I would go with bsxfun any day!
Note: #Divakar posted a very elegant answer using bsxfun, and I'd suggest to use that approach. Still, I am posting this answer (as I already wrote most of it when the other answer was posted), so you can see what was wrong with your existing code.
As your goal is to normalize every row of the matrix X to zero mean and variance 1, then your version doesn't work as expected. As #Dan remarked in a comment, by using / to divide, you do a matrix division between two row vectors, which creates a scalar as result. The output of the loop is therefore a n x 1 column vector (of which I don't know what it actually contains...).
First, realize that mean returns a row vector, where each entry contains the mean of the corresponding column. To normalize row-wise, you have to get the mean of each row, which can be done by mean(X,2). The same goes for std, i.e. use std(X,[],2).
mu = mean(X,2);
sigma = std(X,[],2);
A version using for loops would now be
X_norm = zeros(size(X));
for k= 1:size(X, 1)
X_norm(k,:) = (X(k,:)-mu(k)) ./ sigma(k);
end
i.e. go through all rows and subtract the mean of the row, and divide by the standard deviation.
By using mu(k), you use the correct mean/std dev for every row.
Also, don't forget to preallocate the matrix X_norm for performance reasons.
Another solution for you using repmat is
(X - repmat(mu, length(X), 1)) ./ repmat(sigma, length(X), 1)
This is possibly a little easier to understand than bsxfun. I have posted this solution to demonstrate that to carry out the operation you want you need to replicate your vectors, mu and sigma. repmat can be used for that, : cant.
Additional Reading: Colon Operator in MATLAB
Although, I would recommend going with bsxfun.
If you have the Statistics Toolbox, you can use the built-in function zscore()
X_norm = zscore(X);

MATLAB: Efficient (vectorized) way to apply function on two matrices?

I have two matrices X and Y, both of order mxn. I want to create a new matrix O of order mxm such that each i,j th entry in this new matrix is computed by applying a function to ith and jth row of X and Y respectively. In my case m = 10000 and n = 500. I tried using a loop but it takes forever. Is there an efficient way to do it?
I am targeting two functions dot product -- dot(row_i, row_j) and exp(-1*norm(row_i-row_j)). But I was wondering if there is a general way so that I can plugin any function.
Solution #1
For the first case, it looks like you can simply use matrix multiplication after transposing Y -
X*Y'
If you are dealing with complex numbers -
conj(X*ctranspose(Y))
Solution #2
For the second case, you need to do a little more work. You need to use bsxfun with permute to re-arrange dimensions and employ the raw form of norm calculations and finally squeeze to get a 2D array output -
squeeze(exp(-1*sqrt(sum(bsxfun(#minus,X,permute(Y,[3 2 1])).^2,2)))
If you would like to avoid squeeze, you can use two permute's -
exp(-1*sqrt(sum(bsxfun(#minus,permute(X,[1 3 2]),permute(Y,[3 1 2])).^2,3)))
I would also advise you to look into this problem - Efficiently compute pairwise squared Euclidean distance in Matlab.
In conclusion, there isn't a common most efficient way that could be employed for every function to ith and jth row of X. If you are still hell bent on that, you can use anonymous function handles with bsxfun, but I am afraid it won't be the most efficient technique.
For the second part, you could also use pdist2:
result = exp(-pdist2(X,Y));

Cepstrum deconvolution Matlab code

I have a little code, that should implement cepstrum deconvolution for minimum phase FIR filter design, but being nonmatlab guy I'm struggling with understanding it. Can someone help?
wn = [ones(1,m)
2*ones((n+odd)/2-1,m)
ones(1-rem(n,2),m)
zeros((n+od d)/2-1,m)];
y = real(ifft(exp(fft(wn.*real(ifft(log(abs(fft(x)))))))));
Mainly I don't understand the first line, ".*" symbol in second line and also probably at some point there should be conversion from real to complex domain in the second line, but I have no idea where. Any ideas?
In the first line you are constructing the matrix wn row by row.
.* operator means element-wise multiplication. * alone would mean matrix multiplication.
In fact you should pay attention to the size of x and wn which must be the same for the element-wise multiplication to have sense.
actually there isn't any conversion from real to complex in the second line. There are the functions log, fft, ifft that may return complex values depending on the input.
You can access the Matlab help by the commands help or doc (for example doc ones should produce the documentation of the ones function - this produce a matrix filled with ones of the size specified by it's arguments).
To quickly summon the help when you're inspecting some code you can use Matlab's inline help by pressing the button F1 when the cursor is at the end of a function name (just before the parenthesis).

MATLAB: how to apply function componentwise

Say I have a function calculateStuff(x) that takes in a scalar as parameter and returns a scalar.
Say I have a vector X and I want to apply calculateStuff on every component in X, and get a vector of the results in return and store it in a new vector Y.
Clearly Y=calculateStuff(X) is illegal, is there a way I can do this besides looping?
You have three options:
modify calculateStuff so that it can take arrays and return arrays
write a loop
use arrayfun to hide the loop: Y = arrayfun(#calculateStuff,X)
Most Matlab operations will let you input a matrix and return a matrix. You should be able to re-write calculateStuff() to take a matrix and return a matrix. That is generally MUCH faster than using a for loop. Loops in Matlab are very expensive time-wise.
The sorts of things you need to look at are "dot" versions of normal operations. For example instead of
y = z * x;
do
y = z .* x;
The first will do a matrix multiplication, which is probably not what you want when vectorizing code. The second does an element-by-element multiplication of z and x.
See here and search for "The dot operations".