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

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.

Related

Filling a matrix with vectors in loop and apply operation

I am working on matlab with a matrix. I would like to reproduce this matrix and apply sum for elements in rows.
I have two vectors defined by this code:
unitsvector=1:5;
reordervector=1:3;
Then, I create an empty matrix to store the values:
resultvec=zeros(size(unitsvector,2)*size(reordervector,2),3);
Finally, here is the loop I use but it is not working:
for a=1:length(resultvec)
for b=reordervector
for c=unitsvector
resultvec(a,1)=b;
resultvec(a,2)=c;
resultvec(a,3)=b+c;
end
end
end
How could I reproduce this matrix in matlab. Thanks for your help.
You can use meshgrid for this without a for loop.
[a,b] = meshgrid(1:5,1:3);
M = [a(:) b(:)];
M(:,3) = sum(M,2); % Create third column by summing first two
Why are you looping at all? sum actually has vector support; a simple resultvec = [a(:,1),a(:,2),sum(a,2)] would work.
As to your code: of course it doesn't work. What do you expect to be the contents of a? You create a as a loop index, which runs over the range 1:length(resultvec). Ergo, within each loop iteration a is a scalar. You try to call it like it is a three-element vector. Nor do you define b and c. This might be possible in R, judging where you're coming from, but not in MATLAB.

"Filling up" an empty vector in Matlab by a for loop

I am trying to create a loop code in MATLAB that "fills up" the elements in an empty column vector of size l x 1, called m. As I don't have very much experience in MATLAB, I am unsure if this is the correct way to go about it.
Note: Seeing as i pertains to the complex quantity in matlab, I denote the i-th element of an array as the ii-th element.
l=length(A); %The number of rows in the empty vector we seek as our output;
%so as to preallocate space for this vector.
q=eigencentrality(A);%An lx1 column vector whose ii-th elements are used in the loop.
l1=max(eig(A)); %A scalar used in the loop.
CS=sg_centrality(A); %%An lx1 column vector whose ii-th elements are used in the loop.
%Now for the actual loop that will "fill up" each ii-th entry
%of our empty vector, m.
m=NaN(l,1); %create the empty vector to be "filled up".
for ii=1:l
m(ii,:)=log(q(ii)^2)*sinh(l1)/CS(ii)^1/2;%this is the form that I want each entry
%of m to have. Note how the ii-th element
%of m depends on the corresponding ii-th
%element of CS and q!
end
Is this the right way to go about "filling up" such an empty column vector, m, whose entries depend on the corresponding elements of two other vectors as above?
Cheers!
You can do this completely vectorized. Vectorization is the act of processing data chunks at a time rather than individually as you're doing in your code. In fact, this is one of MATLAB's main advantages. You can replace that for loop with:
m = log(q.^2).*(sinh(l1)./CS).^1/2;
The .* and .^ operators are known as element-wise operators. This means that each value in each of q, li and CS will contribute to the corresponding position in the output. There's no need to use a loop.
Check out this MathWorks note on vectorization here: http://www.mathworks.com/help/matlab/matlab_prog/vectorization.html
You can vectorize all the operations, without using a for loop. This should work:
m=log(q.^2).*(sinh(l1)./CS).^1/2;
Note, that the dots denote elementwise operations. Usually this is much faster than using a loop. Also, just as a side note, you can then drop the preallocation.

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.

Remove duplicates in correlations in matlab

Please see the following issue:
P=rand(4,4);
for i=1:size(P,2)
for j=1:size(P,2)
[r,p]=corr(P(:,i),P(:,j))
end
end
Clearly, the loop will cause the number of correlations to be doubled (i.e., corr(P(:,1),P(:,4)) and corr(P(:,4),P(:,1)). Does anyone have a suggestion on how to avoid this? Perhaps not using a loop?
Thanks!
I have four suggestions for you, depending on what exactly you are doing to compute your matrices. I'm assuming the example you gave is a simplified version of what needs to be done.
First Method - Adjusting the inner loop index
One thing you can do is change your j loop index so that it only goes from 1 up to i. This way, you get a lower triangular matrix and just concentrate on the values within the lower triangular half of your matrix. The upper half would essentially be all set to zero. In other words:
for i = 1 : size(P,2)
for j = 1 : i
%// Your code here
end
end
Second Method - Leave it unchanged, but then use unique
You can go ahead and use the same matrix like you did before with the full two for loops, but you can then filter the duplicates by using unique. In other words, you can do this:
[Y,indices] = unique(P);
Y will give you a list of unique values within the matrix P and indices will give you the locations of where these occurred within P. Note that these are column major indices, and so if you wanted to find the row and column locations of where these locations occur, you can do:
[rows,cols] = ind2sub(size(P), indices);
Third Method - Use pdist and squareform
Since you're looking for a solution that requires no loops, take a look at the pdist function. Given a M x N matrix, pdist will find distances between each pair of rows in a matrix. squareform will then transform these distances into a matrix like what you have seen above. In other words, do this:
dists = pdist(P.', 'correlation');
distMatrix = squareform(dists);
Fourth Method - Use the corr method straight out of the box
You can just use corr in the following way:
[rho, pvals] = corr(P);
corr in this case will produce a m x m matrix that contains the correlation coefficient between each pair of columns an n x m matrix stored in P.
Hopefully one of these will work!
this works ?
for i=1:size(P,2)
for j=1:i
Since you are just correlating each column with the other, then why not just use (straight from the documentation)
[Rho,Pval] = corr(P);
I don't have the Statistics Toolbox, but according to http://www.mathworks.com/help/stats/corr.html,
corr(X) returns a p-by-p matrix containing the pairwise linear correlation coefficient between each pair of columns in the n-by-p matrix X.

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.