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

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.

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 3D matrix multiplication

In Matlab, I have two m-by-n matrices X and Y, with n>m.
I need to define a 3D m-by-m-by-n matrix Z whose components can be computed as
for i=2:m
for j=i+1:m
for k=1:n
Z(i,j,k) = (Y(j-1,k)-Y(i-1,k))*X(j-1,k);
end
end
end
As these nested loops require a long computational time, I have been looking for a way to define the matrix Z using matrices multiplication, but I have not managed so far. Any suggestion?
You can simply remove the inner loop (over k) by writing
Z(i,j,:) = (Y(j-1,:)-Y(i-1,:)).*X(j-1,:);
Note the .* element-wise multiplication. You can then proceed to remove additional loops in a similar manner.
But note that, most likely, your loop is slow because you don't preallocate the output array. Do this before the loop:
Z = zeros(m,m,n);
You can also gain a bit of speed by reversing the loop order, such that the first index is iterated over in the innermost loop, and the last index is iterated over in the outermost loop. This accesses the matrix data in memory order, making your cache more efficient.

What is the colon operator doing here?

What are these lines of code doing?
x0 = rand(n,2)
x0(:,1)=W*x0(:,1)
x0(:,2)=H*x0(:,2)
x0=x0(:)
Is this just one big column vector?
I'd encourage you to take a MATLAB Tutorial as indexing arrays is a fundamental skill. Also see Basic Concepts in MATLAB. Line-by-line descriptions are below to get you started.
What are these lines of code doing?
Let's take this line by line.
1. This line uses rand() to generate an n x 2 matrix of uniform random numbers (~U(0,1)).
x0 = rand(n,2) % Generate nx2 matrix of U(0,1) random numbers
2. Multiply the first column by W
In this case, x0(:,1) means take all rows of x0 (the colon in the first argument) and the 1st column (the 1). Here, the * operator indicates W is a scalar or an appropriately sized array for feasible matrix multiplication (my guess is a scalar). The notation .* can be used for element-by-element multiplication; see here and here for more details.
x0(:,1)=W*x0(:,1) % Multiply (all rows) 1st column by W
3. Multiply the first column by H.
Using similar logic as #2.
x0(:,2)=H*x0(:,2) % Multiply (all rows) 2nd column by H
4. Force column
The x0(:) takes the array x0 and forces all elements into a single column.
From the documentation for colon:
A(:) reshapes all elements of A into a single column vector. This has
no effect if A is already a column vector.
A related operation is forcing a row vector by combining this with the transpose operator.
For example, try the following: x0(:).'
x0 = x0(:) % Force Column
x0 = x0(:).' % Force Row
Related Posts:
What is Matlab's colon operator called?
How does MATLAB's colon operator work?
Combination of colon-operations in MATLAB

Matlab - vector divide by vector, use loop

I have to two evenly sized very large vectors (columns) A and B. I would like to divide vector A by vector B. This will give me a large matrix AxB filled with zeros, except the last column. This column contains the values I'm interested in. When I simple divide the vectors in a Matlab script, I run out of memory. Probably because the matrix AxB becomes very large. Probably I can prevent this from happening by repeating the following:
calculating the first row of matrix AxB
filter the last value and put it into another vector C.
delete the used row of matrix AxB
redo step 1-4 for all rows in vector A
How can I make a loop which does this?
You're question doesn't make it clear what you are trying to do, although it sounds like you want to do an element wise division.
Try:
C = A./B
"Matrix product AxB" and "dividing vectors" are distinct operations.
If we understood this correctly, what you do want to calculate is "C = last column from AxB", such that:
lastcolsel=zeros(size(B,2),1)
C=(A*B)*lastcolsel
If that code breaks your memory limit, recall that matrix product is associative (MxN)xP = Mx(NxP). Simplifying your example, we get:
lastcolsel=zeros(size(B,2),1)
simplifier=B*lastcolsel
C=A*simplifier

matlab: populating a sparse matrix with addition

preface: As the matlab guiderules state, Usually, when one wants to efficiently populate a sparse matrix in matlab, he should create a vector of indexes into the matrix and a vector of values he wants to assign, and then concentrate all the assignments into one atomic operation, so as to allow matlab to "prepare" the matrix in advance and optimize the assignment speed. A simple example:
A=sparse([]);
inds=some_index_generating_method();
vals=some_value_generating_method();
A(inds)=vals;
My question: what can I do in the case where inds contain overlapping indexes, i.e inds=[4 17 8 17 9] where 17 repeats twice.
In this case, what I would want to happen is that the matrix would be assigned the addition of all the values that are mapped to the same index, i.e for the previous example
A(17)=vals(2)+vals(4) %as inds(2)==inds(4)
Is there any straightforward and, most importantly, fast way to achieve this? I have no way of generating the indexes and values in a "smarter" way.
This might help:
S = sparse(i,j,s,m,n,nzmax) uses vectors i, j, and s to generate an m-by-n sparse matrix such that S(i(k),j(k)) = s(k), with space allocated for nzmax nonzeros. Vectors i, j, and s are all the same length. Any elements of s that are zero are ignored, along with the corresponding values of i and j. Any elements of s that have duplicate values of i and j are added together.
See more at MATLAB documentation for sparse function