What is the purpose of the for iteration in the code? - matlab

I have a small code like this. Can anyone tell me what is the purpose of the for iteration?
I can see the result difference before and after the for iteration, I just cannot understand what is
the purpose of the for iteration? Thanks a lot!
A = randn(n,m);
for i=1:m
A(:,i) = A(:,i) / norm(A(:,i));
end

It's ensuring that each column in A is normalised to have unit length.
A(:,1) gives you the first column of A, and norm(A(:,1)) gives you the Euclidean norm (or length) of the vector defined by the first column of A.
The reason that you can't do A=A/norm(A) is because Matlab will calculate the matrix norm, not the norm of each column individually.
There is a Matlab builtin function that will do this for you: normc.

Like David said, it's giving each column unit length, and you can't do A/norm(A) for reasons he mentioned, but you can do:
bsxfun(#rdivide, A, sqrt(sum(A.^2,1)))
which is like virtually doing:
A ./ repmat(sqrt(sum(A.^2,1)),size(A,1),1)
On a side note, I would advise against assigning to the same variable while figuring out an expression.

Related

Dimensional Problem with simple coefficient equation

I am trying to create this function in MATLAB. From a previous question, I have solved for a as agrid2 and f(a) as fx, whose dimensions are 600*1 and 600*2- these two vectors are absolutely correct:
%calculating gini coefficent
m = 600;
for i = 1:m %expanded length of kgrid of ai previously calculated in invarden.m
mu = sum(agrid2.*fx(m,:));
gini = sum(fx(m,1)*(fx(m,2))*abs(fx(m,1)-fx(m,2)))./(2*mu);
end
However, my code is returning all blank answers.
what did I do wrong? Any advice is greatly appreciated!
It is not clear what the matrices agrid2 and fx are, however mu should be computed outside that for loop, since in the formula (1) it is not included in the summation. So, you should first compute mu, and then G.
Furthermore, from your code it seems that inside the function abs() you are considering f instead of a.
Also, I am pretty sure you need a double for loop, since there are two summations in (1).

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.

Matlab own fft2 without loops

I have a problem.
I have a task to write an own fft2 without using for-loops in Matlab.
There is a formula for computing this task:
F(u,v) = sum (0 to M-1) {sum(o to N-1) {f(m,n)*e^(-i*2pi*(um/M + vn/N))}}
Or for better reading:
http://www.directupload.net/file/d/3808/qs3r9ogz_png.htm
It is easy to do it with two for-loops but I have no idea how to do this without these loops, absolutely no idea.
We get no help by the teaching personal. They don't even give a hint or a reference to a book, where we could read about it.
Now, I want to try to get help here.
Are you familiar with the matrix form of DFT? have a look here: http://en.wikipedia.org/wiki/DFT_matrix
You can do something similar in order to get a matrix form for 2D DFT.
You need to transformation matrices. The first is a N-by-N DFT matrix that operates on the columns of f, as explained in the link above. Next you need another M-byM DFT matrix the operates on the rows of f. Finally, you transformed signal is given by
F = Wm * f * Wn;
without any loops.
Note that the DFT matrix can be constructed also without loop by using something like
(1:M)*((1:M)')
Just a little correction in Thp's answer: (1:M)*((1:M)') is not the right way to create the matrix, but (1:M)'*(1:M) is the correct way.

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 to compute all the minors with a given order of a matrix in matlab

I have a matrix m*n,
I want from it all the minors (the determinant of the submatrices) of order p.
I din't found anything good in the documentation, I could do it with a function written by my self, but I'd prefer something out of the box.
My real need is to check when,in a symbolic matrix, I have a fall of rank,and that happens when all the minors of that rank and above are zeros.
Any idea to do it with pure matlab comands? since there is a function to evalutate rank it has get the minors someway.
There appear to be some good answers already, but here is a simple explanation of what you can do:
Suppose you want to know the rank of every i-jth submatrix of a matrix M.
Now i believe the simplest way to get all ranks is to loop over all rows and columns and store this result in a matrix R.
M = magic(5);
R = NaN(size(M));
for i=1:size(M,1);
for j=1:size(M,2);
R(i,j) = rank(M([1:i-1 i+1:end],[1:j-1 j+1:end]));
end
end
If you want all determinants replace rank with det.
This calculates the submatrix:
submatrix=#(M,r,c)M([1:r-1,r+1:end],[1:c-1,c+1:end])
You may either use 'arrayfun' and 'meshgrid' or two loops to iterate over all submatrices.
Caveat: I don't have the Symbolic Toolbox but for a regular matlab array you can calculate the i-th, j-th minor with an anonymous function like this:
minor = #(i,j,A)det(A(setdiff([1:end],[i]),setdiff([1:end],[j])))
Or if you want the i-th, j-th cofactor, simply use:
cofactor = #(i,j,A)(-1)^(i+j)*det(A(setdiff([1:end],[i]),setdiff([1:end],[j])))
But as mentioned I don't know if something like this will work with the Symbolic Toolbox. If it does not work as-is, perhaps this can at least give you some ideas on how you might implement the function for the symbolic case.
Hope this helps.