Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
How to make four nested loops more efficient?

Subject: How to make four nested loops more efficient?

From: Jeff

Date: 2 May, 2013 14:55:09

Message: 1 of 1

I have MATLAB code with four nested 'for..end' loops. It works so long as N is not too large. But it runs very slowly and I have to put my PC in my freezer to keep it from overheating. I am trying to find a way to make it more efficient.

I tried changing the inner for loop (for nn=...) to a parfor loop, but the editor said I cannot do so "due to the way variable 'V' is used" and "Valid indices for 'V' are restricted". I already know that if the inside for loop can't be parallelized, then it's not even worth the minor effort of typing 'par' in front of the outer ones.

Can the following code be made better? If so, how?

% p is a positive integer.
N=2^p;
D=zeros(1, N^2);
V=zeros(N^2);
for jj=1:N
  for kk=1:N
    
    idxVal=(jj-1)*N + kk;
    D(idxVal) = 4 - 2*cosd((jj*180)/(N+1)) - 2*cosd((kk*180)/(N+1));
    
    for mm=1:N
      for nn=1:N
        idxVec = (mm-1)*N+nn;
        V(idxVec,idxVal) = sind((jj*180*mm)/(N+1)) ...
          * sind((kk*180*nn)/(N+1));
      end
    end
  end
end

I am using the student R2009a version.

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us