vectorizing my code
3 views (last 30 days)
Show older comments
can anyone give an idea on how to vectorize my code.
for loop=1:1:10
%X=1*loop*ones(n,4);
%Y=1*loop*ones(n,4)';
X=rand(n,4);
Y=rand(4,n);
U=zeros(n,4);
V=zeros(4,n);
while(norm(U-X)+norm(V-Y)>0.01)
U=X;
V=Y;
for i=1:1:n
f=@(r)norm((D(i,:)-[r(1),r(2),r(3),r(4)]*Y));
X(i,:)=fminsearch(f,[1,1,1,1]);
end
for j=1:1:n
g=@(s)norm((D(:,j)-X*[s(1);s(2);s(3);s(4)]));
Y(:,j)=fminsearch(g, [1;1;1;1]);
end
if(max(max(X*Y))>3)
X=rand(n,4)/10;
Y=rand(4,n)/10;
U=zeros(n,4);
V=zeros(4,n);
end
end
end
Thanks
4 Comments
Roger Stafford
on 29 Apr 2011
Third (embarrassed) comment:
My brain is not up to par today, I'm afraid. What I should have said was the very simple:
X = D/Y;
and
Y = X\D;
in place of the two inner for loops.
As I wrote these earlier I would have been doing some of the matrix divisions' work for them. My apologies.
Answers (2)
Walter Roberson
on 28 Apr 2011
I think you had better explain what you are attempting to accomplish.
3 Comments
Walter Roberson
on 29 Apr 2011
The code as it is now does not use the value of the index variable within the body of the "for" loop. If we examine the body of the "for" loop we see that it has no memory, no reliance on previous iterations: no matter what has gone before, it re-initializes all of the variables. The only memory that that loop has is that it uses different random number values in each iteration. Is it the case that it is important to "advance" the random number generator by a particular amount, or is one set of random numbers as good as another for your purposes? If one set is as good as another, then the way to eliminate the "for" loop is simply to perform what is inside the loop exactly once: that will generate the same answer (statistically speaking) as running it with 10 different sets of random numbers and keeping only the information about the last set.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!