How do i find a matrix of 150*25 from two vectors such that each vector elements multiply with each element of another vector of dim 1*150 &1*25? - matlab

I have a vector created from linspace between specific numbers and have dimensions of 1*150. Now i want to multiply each element of the above created vector with another vector whose dimension is 1*25. The detail of my code is given below
c_p = linspace(1,.3*pi,150);
c = c_p';
C = zeros([150,25]);
for i= 1:1:size(C,1)
wp= c(i);
for n= 1:25
c_wp(n) = cos(n*wp);
end
C(i,25)= c_wp;
end
The vector is actually a multiple of cosine of length 25 and here wp is the elements of first vector of dimension 1*150. SO by the logic, I must have an output of 150*25 but instead giving me "subscripted assignment dimension mismatch". Any help would be appreciated, as i am new to matlab.

To multiply each element of a row vector a with each element of another row vector b, we can use linear algebra. We transpose a to make it a column vector and then use matrix multiplication:
a.' * b
That way you don't even need a for loop.

Related

matlab - ith element of vector is the sum of the first i elements of a different vector

I'm trying to compute a vector A for which the ith element is the sum of the first i elements of a different vector B (this vector is given).
I couldn't work out how to do this and the internet wasn't much help either.
I am very new to matlab so an easy solution would be preferred :)
Use MATLAB's cumsum function.
code example:
%generates random vector b
b = rand(5,1);
%calculates accomulative sum
a = cumsum(b);
Result:
b = [0.4319 0.9616 0.5671 0.8731 0.5730]
a = [0.4319 1.3935 1.9606 2.8338 3.4068]

How can I generalize this function to `n` terms?

I'd like to create a function that adds several gaussian terms of various width over some specified region:
G(a,b,x) = a_1 exp(- b_1 x^2) + a_2 exp(- b_2 x^2) + ... a_N exp(-b_N x^2)
I'd like this function to output an array of length x, summing over the terms of parameters a,b provided, something like:
x = linspace(-2,2,1000);
N_gauss = #(a,b) a(:).*exp(-b(:)*x.^2);
This example actually works if a,b have only a single value, but when they become vectors it no longer works (I suppose Matlab doesn't know what should be added, multiplied or remain a vector). Is this even possible?
You can do this purely by matrix multiplication. Let's tackle the problem slowly and work our way up. You first need to form products of the elements of the vector b and scalar values stored in x. First create a 2D matrix of values where each row corresponds to the product-wise values between an element in b and an element in x. The element (i,j) in this matrix corresponds to the product of the ith element in x with the jth element in b.
You can achieve this by using the outer product. Make x a column vector and b a row vector, then perform the multiplication. Also, make sure you square each of the x terms as seen in your equation.
term1 = (x(:).^2)*b(:).';
Now you can apply the exponential operator and ensure you place a negative in the exponent so you can build the right side of each term (i.e. exp(- b_i x^2)):
term2 = exp(-term1);
The last thing you need to do is multiply each of the values in the 2D matrix with the right coefficient from the a vector. You can do this by enforcing that a be a column vector and performing matrix-vector multiplication.
out = term2*a(:);
Matrix-vector multiplication is the dot product between the column vector a with each row in the 2D matrix we created before. This exactly corresponds to the summation of your equation for each value in x. As such, this achieves the Gaussian summation for each value in x and places this into a n x 1 vector where n is the total number of elements in x. Putting this all together gives us:
out = exp(-(x(:).^2)*b(:).')*a(:);
To finally abstract this into an anonymous function, do:
N_gauss = #(a,b,x) exp(-(x(:).^2)*b(:).')*a(:);
This function takes in the vectors a, b and x as per your problem.

Generate matrix from an index vector

In matlab, I have a matrix and index vector v (in real problem, v vector is very long)
A = [1,2,3;4,5,6;7,8,9]; % 3-by-3 matrix
v = [1,2,3,2,3,3,1]
How can I generate a matrix like
[A(1,:);A(2,:);A(3,:);A(2,:);A(3,:);A(3,:);A(1,:)]
without using loop or write out everything explicitly?
You can use vectors to index, A([1,1,1]) would give you three times the first element.
A(v,:)

Find the minimum difference between any pair of elements between two vectors

Which of the following statements will find the minimum difference between any pair of elements (a,b) where a is from the vector A and b is from the vector B.
A. [X,Y] = meshgrid(A,B);
min(abs(X-Y))
B. [X,Y] = meshgrid(A,B);
min(abs(min(Y-X)))
C. min(abs(A-B))
D. [X,Y] = meshgrid(A,B);
min(min(abs(X-Y)))
Can someone please explain to me?
By saying "minimum difference between any pair of elements(a,b)", I presume you mean that you are treating A and B as sets and you intend to find the absolute difference in any possible pair of elements from these two sets. So in this case you should use your option D
[X,Y] = meshgrid(A,B);
min(min(abs(X-Y)))
Explanation: Meshgrid turns a pair of 1-D vectors into 2-D grids. This link can explain what I mean to say:
http://www.mathworks.com/help/matlab/ref/meshgrid.html?s_tid=gn_loc_drop
Hence (X-Y) will give the difference in all possible pairs (a,b) such that a belongs to A and b belongs to B. Note that this will be a 2-D matrix.
abs(X-Y) would return the absolute values of all elements in this matrix (the absolute difference in each pair).
To find the smallest element in this matrix you will have to use min(min(abs(X-Y))). This is because if Z is a matrix, min(Z) treats the columns of Z as vectors, returning a row vector containing the minimum element from each column. So a single min command will give a row vector with each element being the min of the elements of that column. Using min for a second time returns the min of this row vector. This would be the smallest element in the entire matrix.
This can help:
http://www.mathworks.com/help/matlab/ref/min.html?searchHighlight=min
Options C is correct if you treat A and B as vectors and not sets. In this case you won't be considering all possible pairs. You'll end up finding the minimum of (a-b) where a,b are both in the same position in their corresponding vectors (pair-wise difference).
D. [X,Y] = meshgrid(A,B);
min(min(abs(X-Y)))
meshgrid will generate two grids - X and Y - from the vectors, which are arranged so that X-Y will generate all combinations of ax-bx where ax is in a and bx is in b.
The rest of the expression just gets the minimum absolute value from the array resulting from the subtraction, which is the value you want.
CORRECT ANSWER IS D
Let m = size(A) and n = size(B)
You want to subtract each pair of (a,b) such that a is from vector A and b is from vector B.
meshgrid(A,B) creates two matrices X Y both of size nxm where X have rows sames have vector A while Yhas columns same as vector B .
Hence , Z = X-Y will give you a matrix with n*m values corresponding to the difference between each pair of values taken from A and B . Now all you have to do is to find the absolute minimum among all values of Z.
You can do that by
req_min = min(min(abs(z)))
The whole code is
[X Y ] = meshgrid(A,B);
Z= X-Y;
Z = abs(Z);
req_min = min(min(Z));
You could also use bsxfun instead of meshgrid:
min(min(abs(bsxfun(#minus, A(:), B(:).'))))
Or use pdist2:
min(min(pdist2(A(:),B(:))))

How can I assign a value to the diagonals of a 4-D matrix using linear indexing in MATLAB?

I have a 4-D matrix A of size NxNxPxQ. How can I easily change the diagonal values to 1 for each NxN 2-D submatrix in a vectorized way?
Incorporating gnovice's suggestion, an easy way to index the elements is:
[N,~,P,Q]=size(A);%# get dimensions of your matrix
diagIndex=repmat(logical(eye(N)),[1 1 P Q]);%# get logical indices of the diagonals
A(diagIndex)=1;%# now index your matrix and set the diagonals to 1.
You can actually do this very simply by directly computing the linear indices for every diagonal element, then setting them to 1:
[N,N,P,Q] = size(A);
diagIndex = cumsum([1:(N+1):N^2; N^2.*ones(P*Q-1,N)]);
A(diagIndex) = 1;
The above example finds the N diagonal indices for the first N-by-N matrix (1:(N+1):N^2). Each subsequent N-by-N matrix (P*Q-1 of them) is offset by N^2 elements from the last, so a matrix of size PQ-1-by-N containing only the value N^2 is appended to the linear indices for the diagonal of the first matrix. When a cumulative sum is performed over each column using the function CUMSUM, the resulting matrix contains the linear indices for all diagonal elements of the 4-D matrix.
You can use direct indexing, and some faffing about with repmat, to add the indexes for a single 50x50 diagonal to the offsets within the larger matrix of each 50x50 block:
Here's an example for a smaller problem:
A = NaN(10,10,5,3);
inner = repmat(sub2ind([10 10], [1:10],[1:10]), 5*3, 10); % diagonals
outer = repmat([10*10 * [0:5*3-1]]', 1, 10*10); % offsets to blocks
diags = inner + outer;
A(diags(:)) = 1;