Thread Subject: Vectorizing 'for' Loops

Subject: Vectorizing 'for' Loops

From: Erik

Date: 19 Aug, 2009 22:43:03

Message: 1 of 2

Hi,

I have an algorithm that involves sweeping over all possible values of 4 different parameters. The logical solution would be to use a for loop; however, this is kind of slow in cases.

My first thought was to use meshgrid, but it only seems to accept a maximum of 3 parameters, i.e. [x,y,z] = meshgrid(1:10,1:10,1:10). The moment I try to add a fourth parameter, it gives me an error.

My next idea was to use ndgrid. However, this is giving me many more cases than I need for a reason I am not sure of. For example,

vec = 1:20;
for p = vec
    for q = vec
        for r = vec
            for s = vec
                ... blah ...
            end
        end
    end
end

gives a different result than,

[p,q,r,s] = ndgrid(vec,vec,vec,vec)
... blah ...

Why??

Thanks

Subject: Vectorizing 'for' Loops

From: Matt

Date: 19 Aug, 2009 23:02:03

Message: 2 of 2

"Erik" <emiehling@gmail.com> wrote in message <h6hv5n$abp$1@fred.mathworks.com>...
> Hi,
>
> I have an algorithm that involves sweeping over all possible values of 4 different parameters. The logical solution would be to use a for loop; however, this is kind of slow in cases.
>
> My first thought was to use meshgrid, but it only seems to accept a maximum of 3 parameters, i.e. [x,y,z] = meshgrid(1:10,1:10,1:10). The moment I try to add a fourth parameter, it gives me an error.
>
> My next idea was to use ndgrid. However, this is giving me many more cases than I need for a reason I am not sure of. For example,
>
> vec = 1:20;
> for p = vec
> for q = vec
> for r = vec
> for s = vec
> ... blah ...
> end
> end
> end
> end
>
> gives a different result than,
>
> [p,q,r,s] = ndgrid(vec,vec,vec,vec)
> ... blah ...
>


Because you've invoked ndgrid such that p is your fastest varying variable, whereas in your for loop it is the slowest. Doing this instead should bring them into consistency:

[s,r,q,p] = ndgrid(vec,vec,vec,vec)

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

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.

Tag Activity for This Thread
Tag Applied By Date/Time
for loop Erik 19 Aug, 2009 18:44:06
meshgrid Erik 19 Aug, 2009 18:44:06
ndgrid Erik 19 Aug, 2009 18:44:06
rssFeed for this Thread

Contact us at files@mathworks.com