apply function to each column of a matrix (Vectorizing) - matlab

What is fastest way of applying function on each column of a matrix without looping through it?
The function I am using is pwelch but the concept should be the same for any function.
Currently I am looping though my matrix as such.
X = ones(5);
for i = 1:5 % length of the number of columns
result = somefunction(X(:,i))
end
Is there a way to vectorize this code?

You say
the concept should be the same for any function
Actually that's not the case. Depending on the function, the code that calls it can be made vectorized or not. It depends on how the function is written internally. From outside the function there's nothing you can do to make it vectorized. Vectorization is done within the function, not from the outside.
If the function is vectorized, you simply call it with a matrix, and the function works on each column. For example, that's what sum does.
In the case of pwelch, you are lucky: according to the documentation (emphasis added),
Pxx = pwelch(X) returns the Power Spectral Density (PSD) estimate, Pxx, ...
When X is a matrix, the PSD is
computed independently for each column and stored in the corresponding
column of Pxx.
So pwelch is a vectorized function.

Related

How to plot a function with an exponential multiplied by a sine function?

Hello I need help plotting the below equation in matlab.
v=10.0004+10.229*e^(-3*t)*sin(5.196*t-257.856)
here is what I have but I keep getting an error:
t=[0:0.1:2];
v=10.0004+10.229*exp(t)*sin(5.196*t+257.856);
plot(t,v)
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the
number of rows in the second matrix. To perform elementwise multiplication, use '.*'.
Error in example (line 2)
v=10.0004+10.229*exp(t)*sin(5.196*t+257.856);
Because t is a matrix, you cannot simply input it as you would a single variable. You have to access each value individually and calculate a corresponding v, then you store that value and move on. Rinse and repeat for each value.
This can be visualized with a for loop. Get the length of your time variable, which will determine how many values you need to calculate, then let the loop run for the corresponding number of elements. Make sure the loop counter is also used to index each element in v.
t = 0:0.1:2 ;
%For each element (n) in t, create a corresponding one of v.
for n = 1:length(t)
v(n) = 10.0004+10.229*exp(t(n))*sin(5.196*t(n)+257.856);
end
plot(t,v)
As we can interpret from the loop, there is a need to do element-wise (good keyword to remember) multiplication. In other languages, you might HAVE to use the loop method. Luckily in Matlab there is a dedicated operator for this '.*'. Therefore in Matlab you could simply modify your code as follows:
t=[0:0.1:2];
v=10.0004+10.229.*exp(t).*sin(5.196.*t+257.856);
plot(t,v)
Either method gives you the desired plot. The first I included to illustrate the underlying logic of what you're looking to do, and the second to simply it with Matlab's syntax. Hope this helps guide you in the future.
Best of luck out there.

Matlab. Poisson fit. Factorial

I have a histogram that seems to fit a poisson distribution.
In order to fit it, I declare the function myself as follows
xdata; ydata; % Arrays in which I have stored the data.
%Ydata tell us how many times the xdata is repeated in the set.
fun= #(x,xdata) (exp(-x(1))*(x(1).^(xdata)) )/(factorial(xdata)) %Function I
% want to use in the fit. It is a poisson distribution.
x0=[1]; %Approximated value of the parameter lambda to help the fit
p=lsqcurvefit(fun,x0,xdata,ydata); % Fit in the least square sense
I find an error. It probably has to do with the "factorial". Any ideas?
Factorial outputs a vector from vector xdata. Why are you using .xdata in factorial?
For example:
data = [1 2 3];
factorial(data) is then [1! 2! 3!].
Try ./factorial(xdata) (I cannot recall if the dot is even necessary at this case.)
You need to use gamma(xdata+1) function instead of factorial(xdata) function. Gamma function is a generalized form of factorial function which can be used for real and complex numbers. Thus, your code would be:
fun = #(x,xdata) exp(-x(1))*x(1).^xdata./gamma(xdata+1);
x = lsqcurvefit(fun,1,xdata,ydata);
Alternatively, you can MATLAB fitdist function which is already optimized and you might get better results:
pd = fitdist(xdata,'Poisson','Frequency',ydata);
pd.lambda

Create a function handle within a structure, given some coefficients

I have a vector of coefficients available, which are the coefficients of an interpolating polynomial. I want to create a field in a structure as follows:
p.val =#(y) polynomial
Here polynomial is the polynomial with my coefficients in the indeterminate y. I'm not sure how to do this. The field has to contain a function handle like this.
The user has to be able to call this as follows:
pval = p.val(y)
where, y can be a vector of any length, supplied by the user (which contains values where the polynomial needs to be evaluated). So, this output has to be a column vector, such that every cell contains the specific function value.
Any help on how this can be done is appreciated!
I am not sure what function you want to implement, but the length of the vector you are including does not matter.
example.a = 3; % Any variable
example.b = #(s) mean(s);
The function mean here can be anything from a built-in function to a custom function you just made.
You can call it by:
result = example.b(rand(1000,1);

How can I use NxM matrix to be my initial condition in `pdepe`

I solved a PDE using Matlab solver, pdepe. The initial condition is the solution of an ODE, which I solved in a different m.file. Now, I have the ODE solution in a matrix form of size NxM. How I can use that to be my IC in pdepe? Is that even possible? When I use for loop, pdepe takes only the last iteration to be the initial condition. Any help is appreciated.
Per the pdepe documentation, the initial condition function for the solver has the syntax:
u = icFun(x);
where the initial value of the PDE at a specified value of x is returned in the column vector u.
So the only time an initial condition will be a N x M matrix is when the PDE is a system of N unknowns with M spatial mesh points.
Therefore, an N x M matrix could be used to populate the initial condition, but there would need to be some mapping that associates a given column with a specific value of x. For instance, in the main function that calls pdepe, there could be
% icData is the NxM matrix of data
% xMesh is an 1xM row vector that has the spatial value for each column of icData
icFun = #(x) icData(:,x==xMesh);
The only shortcoming of this approach is that the mesh of the initial condition, and therefore the pdepe solution, is constrained by the initial data. This can be overcome by using an interpolation scheme like:
% icData is the NxM matrix of data
% xMesh is an 1xM row vector that has the spatial value for each column of icData
icFun = #(x) interp1(xMesh,icData',x,'pchip')';
where the transposes are present to conform to the interpretation of the data by interp1.
it is easier for u to use 'method of line' style to define different conditions on each mesh rather than using pdepe
MOL is also more flexible to use in different situation like 3D problem
just saying :))
My experience is that the function defining the initial conditions must return a column vector, i.e. Nx1 matrix if you have N equations. Even if your xmesh is an array of M numbers, the matrix corresponding to the initial condition is still Nx1. You can still return a spatially varying initial condition, and my solution was the following.
I defined an anonymous function, pdeic, which was passed as an argument to pdepe:
pdeic=#(x) pdeic2(x,p1,p2,p3);
And I also defined pdeic2, which always returns a 3x1 column vector, but depending on x, the value is different:
function u0=pdeic2(x,extrap1,extrap2,extrap3)
if x==extrap3
u0=[extrap1;0;extrap2];
else
u0=[extrap1;0;0];
end
So going back to your original question, my guess would be that you have to pass the solution of your ODE to what is named 'pdeic2' in my example, and depending on X, return a column vector.

How can I integrate a function which needs to have a matrix calculation first?

I am doing my dissertation now. I stuck with a integral. My function is defined as
myfun =(exp(t*Q)*V*x)(j);
where Q and V are a matrix (n*n), x is a vector which elements are 1, then after calculation we get the j_th element of that vector then I need to integrate the function against t.
I want to use the quad in the matlab. However the point is that it will report the inner matrix is not the same size. Since A here is not a number ?....
How can I do this. Otherwise I could only write a loop against t itself, which is extremely slow.
Thanks
You can use SUBSREF for this (you still neet to loop over all j's, though):
myfunOfT = #(t)(subsref(exp(t*Q)*V*x,struct('type','()','subs',j);
This returns the value of the jth element of the array at time t.