Thread Subject: need help improving embedded for loop!

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 12 Jul, 2009 01:43:03

Message: 1 of 23

I really hate making other people spend their valuable time helping me code... because it's really something I should be able to do on my own ... but I've been thinking about this for so long now and I think I'm brain dead... )=


The following code generates all permutations of 'ABCD' of length 3. It will also generate all length 3 permutates of 'ABCDEFGH...' if the frist line is appropriately changed. The only problem is that it's not very easy to make it generalizable to permutations of length n, for any integer n:

A='ABCD';
z=1;
for a=1:length(A) for b=1:length(A) for c=1:length(A)
            A3(z,1)=A(a);
            A3(z,2)=A(b);
            A3(z,3)=A(c);
            A3(z,4:6)='(i)';
            z=z+1; end
            end
        end
---------
There's two ways I went about trying to generalize this:
----
1:
-----
A='ABC';
z=1;indices={'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o'};
for y=1:stringLength
    for indices{y}=1:length(A)
            string(z,y)=A(indices(y));
            z=z+1;
            end
            string(z,stringLength+1:stringLength+3)='(i)';
        end
-------
This probably can turn out to work with the use of the 'eval' command and 'poofing' variables into existence, but it's been strongly recommended not to do so
-------
2:
-------
indices=zeros(stringLength,length(A));
for i=1:length(A) indices(:,i)=i; end
z=1;
for i=1:stringLength
    for j=1:length(A)
       string(z,j)=A(1,indices(i,j));
    end
    z=z+1;
end
------
But this is not working and I'm not sure what the best way to proceed from here is
-----

I'm really sorry for wasting forum space with something so simple but I've been programming all week and feel brain dead. Any help is appreciated. Another suggestion compeletely different from the above three would also be keenly considered.

Or even better ... is there an internal function that generates all permuations ??

THANK YOU! xoxo

Subject: need help improving embedded for loop!

From: dpb

Date: 12 Jul, 2009 02:16:13

Message: 2 of 23

Juliette Salexa wrote:
...
> Or even better ... is there an internal function that generates all permuations ??

 >> lookfor permutation
PERMS All possible permutations.
COLAMD Column approximate minimum degree permutation.
COLMMD Column minimum degree permutation.
COLPERM Column permutation.
DMPERM Dulmage-Mendelsohn permutation.
RANDPERM Random permutation.
SYMAMD Symmetric approximate minimum deg
...

--

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 12 Jul, 2009 03:00:06

Message: 3 of 23

Yes I looked at those before I started writing my own function!
Those don't do what I want.

This one claims to:
http://www.mathworks.com/matlabcentral/fileexchange/11462

and surely DOES for integers (even faster than mine by 0.000879 seconds for n=[1 2 3 4],k=3), but for characters, copying and pasting the command from the documentation gives:

MAT = npermutek(['a' 'b' 'c'],2)
??? Subscripted assignment dimension mismatch.

Error in ==> npermutek at 89
Matrix(:,K) = TMP(:); % We don't need to do two these in loop.


.... I also, at first glance, can't follow the algorithm.... and it takes about 80 lines more of code than mine..... so if there's a way to fix my "for loop of for loops" i'm sure that 0.000879 seconds of speed will be compensated and i'll have a more robust code.

Subject: need help improving embedded for loop!

From: dpb

Date: 12 Jul, 2009 04:16:37

Message: 4 of 23

Juliette Salexa wrote:
> Yes I looked at those before I started writing my own function!
> Those don't do what I want.
>
...

 >> s(perms(1:4))
ans =
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc

--

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 12 Jul, 2009 06:25:03

Message: 5 of 23

dbp, what is your funciton s doing ??

Subject: need help improving embedded for loop!

From: dpb

Date: 12 Jul, 2009 12:47:25

Message: 6 of 23

Juliette Salexa wrote:
> dbp, what is your funciton s doing ??

s = 'abcd';

--

Subject: need help improving embedded for loop!

From: dpb

Date: 12 Jul, 2009 15:15:21

Message: 7 of 23

dpb wrote:
> Juliette Salexa wrote:
>> dbp, what is your funciton s doing ??
>
> s = 'abcd';

Clipped previous reply, sorry...

s is simply a character string and s(perms(1:4)) simply demonstrated you
_can_ permute characters via indexing as a "kickstart" per your last
request of another way to think of your problem.

Not knowing precisely your requirements it may not directly solve the
problem but it might be a thinker...

The largest problem w/ perms() if your sizes get large could be memory
in that it generates the full matrix up to memory limitations.

--

Subject: need help improving embedded for loop!

From: dpb

Date: 12 Jul, 2009 15:38:45

Message: 8 of 23

Juliette Salexa wrote:
> Yes I looked at those before I started writing my own function!
> Those don't do what I want.
...

Actually, iiuc, what you're asking for is given by nchoosek() I believe...

Try wrapping the following in a function and see if it doesn't suit as
long as don't try to get too large...

s = 'abcedfg';
permlen = 3;

s(nchoosek([1:length(s)], permlen))

--

Subject: need help improving embedded for loop!

From: Matt Fig

Date: 12 Jul, 2009 19:14:02

Message: 9 of 23

"Juliette Salexa" <juliette.physicist@gmail.com> wrote in message <h3bf37$ik0$1@fred.mathworks.com>...
> I really hate making other people spend their valuable time helping me code... because it's really something I should be able to do on my own ... but I've been thinking about this for so long now and I think I'm brain dead... )=
>
>
> The following code generates all permutations of 'ABCD' of length 3. It will also generate all length 3 permutates of 'ABCDEFGH...' if the frist line is appropriately changed. The only problem is that it's not very easy to make it generalizable to permutations of length n, for any integer n:

> Or even better ... is there an internal function that generates all permuations ??
>
> THANK YOU! xoxo

Exactly what I wrote COMBINATOR to do:

Numbers 1,2,3,4 taken 2 at a time:

I = combinator(4,2,'p','r') % Permutations with repetition
I = combinator(4,2,'p') % Permutations without repetition
I = combinator(4,2,'c','r') % Combinations with repetition
I = combinator(4,2,'c') % Combinations without repetition

Then use I as an index into your set.


http://www.mathworks.com/matlabcentral/fileexchange/24325

Subject: need help improving embedded for loop!

From: Matt Fig

Date: 12 Jul, 2009 20:53:00

Message: 10 of 23

"Juliette Salexa" <juliette.physicist@gmail.com> wrote in message <h3bjjm$764$1@fred.mathworks.com>...
> Yes I looked at those before I started writing my own function!
> Those don't do what I want.
>
> This one claims to:
> http://www.mathworks.com/matlabcentral/fileexchange/11462
>
> and surely DOES for integers (even faster than mine by 0.000879 seconds for n=[1 2 3 4],k=3), but for characters, copying and pasting the command from the documentation gives:
>
> MAT = npermutek(['a' 'b' 'c'],2)
> ??? Subscripted assignment dimension mismatch.
>
> Error in ==> npermutek at 89
> Matrix(:,K) = TMP(:); % We don't need to do two these in loop.
>


What version of MATLAB are you using? This works on my R2007a. Please let me know, as this is my file and I want to keep track of why it doesn't work.



>> MAT = npermutek(['a' 'b' 'c'],2)
MAT =
aa
ab
ac
ba
bb
bc
ca
cb
cc

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 13 Jul, 2009 00:00:20

Message: 11 of 23

Thank you dpb,
I realized how to do it while I was in the shower today.. and it was based on your suggestion of using perms.

Thank you Matt Fig,

I copied and pasted it into matlab just now (R2007b):

>> clear('all')
>> MAT = npermutek(['a' 'b' 'c'],2)
??? Subscripted assignment dimension mismatch.

Error in ==> npermutek at 89
Matrix(:,K) = TMP(:); % We don't need to do two these in loop.

Subject: need help improving embedded for loop!

From: Matt Fig

Date: 13 Jul, 2009 01:49:03

Message: 12 of 23

"Juliette Salexa" <juliette.physicist@gmail.com> wrote in message
> Thank you Matt Fig,
>
> I copied and pasted it into matlab just now (R2007b):
>
> >> clear('all')
> >> MAT = npermutek(['a' 'b' 'c'],2)
> ??? Subscripted assignment dimension mismatch.
>
> Error in ==> npermutek at 89
> Matrix(:,K) = TMP(:); % We don't need to do two these in loop.

Well I have had an upgrade of 2007b laying around, but I just never installed it because I liked 2007a so much. This motivated me to do it. Unfortunately it didn't clear up anything. I am now really confused. Here is my screen output.


>> version
ans =
7.5.0.342 (R2007b)
>> computer
ans =
PCWIN
>> clear('all')
>> MAT = npermutek(['a' 'b' 'c'],2)
MAT =
aa
ab
ac
ba
bb
bc
ca
cb
cc
>> Str = ['a' 'b' 'c'] % Try this another way.
Str =
abc
>> Str(npermutek(1:3,2))
ans =
aa
ab
ac
ba
bb
bc
ca
cb
cc
>>


No problems at all. I have no clue as to why this isn't working on your system.
Well, I am glad you figured it out another way!

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 13 Jul, 2009 02:43:02

Message: 13 of 23

My output:

>> version
ans =
7.5.0.342 (R2007b)
>> computer
ans =
PCWIN
>> clear('all')
>> MAT=npermutek(['a' 'b' 'c'],2)
??? Subscripted assignment dimension mismatch.
Error in ==> npermutek at 89
Matrix(:,K) = TMP(:); % We don't need to do two these in loop.

>> Str=['a' 'b' 'c']
Str =
abc
>> Str(npermutek(1:3,2))
ans =
aa
ab
ac
ba
bb
bc
ca
cb
cc

-----
which is what I expected would happen when doing it the second way, because as I said at the beginning, your code worked for me for integers all along, it was only for characters that it didn't work.

Hmmm...
at this point I've been using my own code with the internal PERMS function, so it doesn't really matter much to me ... but if you're still concerned, maybe it's just that the version I downloaded was older than the version you're using ??

your code didn't have a "date of last update" mentioned anywhere, but I downloaded it from the link I posted earlier in this thread.

Subject: need help improving embedded for loop!

From: Matt Fig

Date: 13 Jul, 2009 02:54:03

Message: 14 of 23

"Juliette Salexa" <juliette.physicist@gmail.com> wrote in message
> which is what I expected would happen when doing it the second way, because as I said at the beginning, your code worked for me for integers all along, it was only for characters that it didn't work.
>
> Hmmm...
> at this point I've been using my own code with the internal PERMS function, so it doesn't really matter much to me ... but if you're still concerned, maybe it's just that the version I downloaded was older than the version you're using ??
>
> your code didn't have a "date of last update" mentioned anywhere, but I downloaded it from the link I posted earlier in this thread.



Thanks Juliette for replying. I too wondered about the version, but that cannot be the source of the problem because I downloaded the file again (from the link you posted) and switched pwd to the new, unzipped folder. Then, of course, I checked with 'which' to make sure I was using the freshly downloaded file and ran the code I showed above.

I guess it is a mystery we will not be able to solve! Oh well, the ghost in the machine strikes again. Since that file has been on the FEX for several years now and no one has contacted me to say that it didn't work with any version, I am not too worried about it.

Thanks.

Subject: need help improving embedded for loop!

From: dpb

Date: 13 Jul, 2009 02:54:43

Message: 15 of 23

Juliette Salexa wrote:
> Thank you dpb, I realized how to do it while I was in the shower
> today.. and it was based on your suggestion of using perms.
>
...
Glad it helped...

Curious minds want to know... what did you implement? :)

BTW, as another curiousity, does the nchoosek() solution do what you wanted?

--

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 13 Jul, 2009 18:17:04

Message: 16 of 23

Hi jpb,
--------------------------
> Curious minds want to know... what did you implement? :)
--------------------------
I ended up writing a code inspired by matt fig's npermutek.m, since his .m file didn't work on my computer for some reason :(

your suggestion: s='ab' ; s(perms(1:2))
was a good idea but doesn't do permutations WITH repetition, it generates 'ab' and 'ba' but not aa and bb.
--------------------------
> BTW, as another curiousity, does the nchoosek() solution do what you wanted?
--------------------------
I didn't try the choose function because the overall goal was to generate permutations with repetitions and not combintations. Although mixing the nchoosek function with other commands in a very clever way might do the trick .. but i have so many things to do right now that trial and error is not worth my time right now, since I already have a working code!
--------------------------
That being said, if anyone knows a way around my forloop problem:

A='ABC';
z=1;
for a=1:length(A) for b=1:length(A) for c=1:length(A) % d=... e=...
            A3(z,1)=A(a);
            A3(z,2)=A(b);
            A3(z,3)=A(c);
% ................. do the same for d, e , up to , let's say n
            z=z+1; end
            end
        end
---------
I would be very curious!! Even though I've solved the problem at hand, I might like to be able to do "for loops of for loops" in the future.

There's two ways I went about trying to generalize this:
----
1:
-----
A='ABC';
z=1;indices={'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o'};
for y=1:stringLength
    for indices{y}=1:length(A)
            string(z,y)=A(indices(y));
            z=z+1;
            end
        end
-------
This probably can turn out to work with the use of the 'eval' command and 'poofing' variables into existence, but it's been strongly recommended not to do so
-------
2:
-------
indices=zeros(stringLength,length(A));
for i=1:length(A) indices(:,i)=i; end
z=1;
for i=1:stringLength
    for j=1:length(A)
       string(z,j)=A(1,indices(i,j));
    end
    z=z+1;
end
-----
This doesn't work, and I'm not sure if it has potential.

Thanks!

Subject: need help improving embedded for loop!

From: dpb

Date: 13 Jul, 2009 19:04:10

Message: 17 of 23

Juliette Salexa wrote:
...
> your suggestion: s='ab' ; s(perms(1:2))
> was a good idea but doesn't do permutations WITH repetition, ,,,

Uhhh, did your original request mention that??? <VGB>

...
> ... Even though I've solved the problem at
> hand, I might like to be able to do "for loops of for loops" in the future.
...

I didn't really look at this but on first blush it seems to me a place
where arrays of cells or other structures might be "more better suited..."

--

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 13 Jul, 2009 19:25:22

Message: 18 of 23

> > your suggestion: s='ab' ; s(perms(1:2))
> > was a good idea but doesn't do permutations WITH repetition, ,,,
>
> Uhhh, did your original request mention that??? <VGB>

Sorry, no I didn't mentioned that I needed repetition. I thought that was apparent by the first block of code there, but now I realize I should have mentioned it. What's VGB?

>
> I didn't really look at this but on first blush it seems to me a place
> where arrays of cells or other structures might be "more better suited..."
>

Hmm.. I have barely used cell arrays and matlab structures before .. how could I use them to solve my loop within a loop problem ??

I would think that based on the frist block of code I put up, such a thing would be very 'foor loop-able' since it is so repetitive.

Subject: need help improving embedded for loop!

From: dpb

Date: 13 Jul, 2009 20:28:36

Message: 19 of 23

Juliette Salexa wrote:
>>> your suggestion: s='ab' ; s(perms(1:2))
>>> was a good idea but doesn't do permutations WITH repetition, ,,,
>> Uhhh, did your original request mention that??? <VGB>
>
> Sorry, no I didn't mentioned that I needed repetition. I thought that
> was apparent by the first block of code there, but now I realize I
> should have mentioned it. What's VGB?

dyslexic <VBG>

>> I didn't really look at this but on first blush it seems to me a place
>> where arrays of cells or other structures might be "more better suited..."
>>
>
> Hmm.. I have barely used cell arrays and matlab structures before ..
> how could I use them to solve my loop within a loop problem ??
>
> I would think that based on the frist block of code I put up, such a
> thing would be very 'foor loop-able' since it is so repetitive.

It seemed to me you were back to the problem of trying to in essence
poof variables by expanding loop nesting dynamically and using explicit
loops/variables.

A cell array could contain another vector or matrix and be added to
inside the same hierarchy.

The proper generalization seems to me to be to remove the need for an
arbitrary number of variables.

--

Subject: need help improving embedded for loop!

From: dpb

Date: 14 Jul, 2009 19:58:27

Message: 20 of 23

Juliette Salexa wrote:
...
> indices=zeros(stringLength,length(A));
> for i=1:length(A) indices(:,i)=i; end
> z=1;
> for i=1:stringLength
> for j=1:length(A)
> string(z,j)=A(1,indices(i,j));
> end
> z=z+1;
> end
> -----
> This doesn't work, and I'm not sure if it has potential.
...

It's hotter 'n blazes here so I'm inside this pm and didn't see any
other particularly interesting posts so came back to this...

Is it too much to ask what your objective here is, again???

--

Subject: need help improving embedded for loop!

From: Juliette Salexa

Date: 14 Jul, 2009 20:44:02

Message: 21 of 23

> It seemed to me you were back to the problem of trying to in essence
> poof variables by expanding loop nesting dynamically and using explicit
> loops/variables.

I was trying to avoid poofing variables here, but it does seem like the most natural thing to do.

>
> A cell array could contain another vector or matrix and be added to
> inside the same hierarchy.
>

Hmm...
Well, I only really found out what a cell array was about a week back and I'm not too familiar with using them. Basically, it's an array whose elements are themselves matrices ??
I'm still not sure how I would use such a structure to do what I want ..
The majority of my programming experience is in FORTRAN 77 and I've only started to use matlab recently, so my brain doesn't seem to be grasping these new data structures very well. Hopefully with more experience I won't have to ask these types of questions on a forum again.

> The proper generalization seems to me to be to remove the need for an
> arbitrary number of variables.
 
If I remove that need, then I'm introducing the need to change my code whenever I do this for a different number of variables. And for a 1000 variables, that would mean I'd have to type out "for" and "end" and some other stuff 1000 times!

> Is it too much to ask what your objective here is, again???

The objective is to do something like:
-------------------------------
A='AB';
z=1;
for a=1:length(A) for b=1:length(A) for c=1:length(A) % for d=... for e=...
            A3(z,1)=A(a);
            A3(z,2)=A(b);
            A3(z,3)=A(c);
% ................. do the same for d, e , up to , let's say n
            z=z+1; end
            end
        end
-------------------------------
I should be able to enter an integer input, let's say, 8, and my output should be:

A3=

AAAAAAAA
AAAAAAAB
AAAAAABA
AAAAAABB
...
...
...
BBBBBBBA
BBBBBBBB
-------------------------------
Mind you, I already have a program that can do this, based partially on Matt Fig's code, now I'm just wondering how to modify the above algorithm so that instead of typing in

for a=1:length(A) for b=1:length(A) for c=1:length(A) % for d=... for e=...

I have a loop that replaces all those for loops.

Subject: need help improving embedded for loop!

From: Matt Fig

Date: 14 Jul, 2009 21:19:01

Message: 22 of 23

"Juliette Salexa" <juliette.physicist@gmail.com> wrote in message
> I should be able to enter an integer input, let's say, 8, and my output should be:
>
> A3=
>
> AAAAAAAA
> AAAAAAAB
> AAAAAABA
> AAAAAABB
> ...
> ...
> ...
> BBBBBBBA
> BBBBBBBB
> -------------------------------
> Mind you, I already have a program that can do this, based partially on Matt Fig's code, now I'm just wondering how to modify the above algorithm so that instead of typing in
>
> for a=1:length(A) for b=1:length(A) for c=1:length(A) % for d=... for e=...
>
> I have a loop that replaces all those for loops.


This can be done with a single loop, in fact I have done so, but it will be much slower than the solution we discussed through email.

Subject: need help improving embedded for loop!

From: dpb

Date: 14 Jul, 2009 21:27:35

Message: 23 of 23

Juliette Salexa wrote:
...
> I was trying to avoid poofing variables here, but it does seem like
> the most natural thing to do.

That's generally the first solution of the ML initiate, yes, but rarely
the best solution as has been discussed before...

>> A cell array could contain another vector or matrix and be added to
>> inside the same hierarchy.
...
> an array whose elements are themselves matrices ??

Yes.

> ...how I would use such a structure to do what I want ..
...
Well, as stated earlier, I don't know that I know it's the ideal
solution; as before I was trying to push into thinking about
alternatives. I have a sorta' half-baked idea but before I trotted it
out I thought I'd be sure was really headed in the direction desired...

>> The proper generalization seems to me to be to remove the need for
>> an arbitrary number of variables.
>
> If I remove that need, then I'm introducing the need to change my
> code whenever I do this for a different number of variables. And for
> a 1000 variables, that would mean I'd have to type out "for" and
> "end" and some other stuff 1000 times!

No! (a thousand times!!!! :) )

That's the whole idea--reduce the problem to a data structure that can
be handled at arbitrary depth by reference, _NOT_ by creating some
ungodly list of separate variables...

With the commensurate result that then the rest of the program also
doesn't have to deal w/ arbitrary number(s) of variables--they can
simply be input/output labels for human, not machine, consumption.

>> Is it too much to ask what your objective here is, again???

> The objective is to do something like:
> A='AB';
> z=1;
> for a=1:length(A)
> for b=1:length(A)
> for c=1:length(A)
> %for d=...
> %for e=...
> A3(z,1)=A(a);
> A3(z,2)=A(b);
> A3(z,3)=A(c);
> % ................. do the same for d, e, up to , let's say n
> z=z+1;
> end
> end
> end
 >
> I should be able to enter an integer
> input, let's say, 8, and my output should be:
>
> A3=
> AAAAAAAA
> AAAAAAAB
> AAAAAABA
> AAAAAABB
> ...
> ...
> ...
> BBBBBBBA
> BBBBBBBB

> Mind you, I already have a program
> that can do this, based partially on Matt Fig's code, now I'm just
> wondering how to modify the above algorithm so that instead of typing
> in [arbitrary number of nested for's]
> I have a loop that replaces all those for loops.

I gotcha'...

I understood you did have the above algorithm working; just wanted to be
sure you were still thinking on the same problem rather than some other.

It (replacing the loops and arbitrary variables) surely would be my long
term objective if it were my project. I can see "quick 'n dirty" (or as
my buddy in Rochester used to say "cheap but cheery" regarding a rather
rundown old hotel at which we used to stay) to get something going but
if the problem domain is really going to grow it isn't a scalable
solution at all.

As noted, it was slow day outside, harvest is done and so I was looking
for a diversion...

I may (or again may not) be back... (unlike MacArthur, I'll deliberately
refrain from "will" :) )

--

Tags for this Thread

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.

rssFeed for this Thread

Contact us at files@mathworks.com