Prev: Transportation problem
Next: cash on delivery louis vuitton shoes versace sneakers puma men trainers creative recreation shoes
From: Juliette Salexa on 27 Dec 2009 15:27 "Steven Lord" <slord(a)mathworks.com> wrote in message > Yes. > > A = 'AB'; > nvariables = 5; > clear c > [c{1:nvariables}] = ndgrid(A); > A3 = repmat(' ', numel(c{1}), nvariables); > for k = 1:nvariables > A3(:, k) = c{k}(:); > end > > Or, if you don't like comma-separated lists and don't mind the combinations > being in a little different order: > > A = 'ABC'; > nvariables = 5; > len = numel(A); > numCombs = len^nvariables; > ind = dec2base(0:(numCombs-1), len); > A(ind-'0'+1) ---------------------------------------------------------- Steve Lord you are a genius! This was very helpful, although it's probably going to take me a long time to decipher what you're doing. Only an expert like you could come up with something that clever!
From: Juliette Salexa on 27 Dec 2009 16:17
"Juliette Salexa" <juliette.physicist(a)gmail.com> wrote in message > Steve Lord you are a genius! > > This was very helpful, although it's probably going to take me a long time to decipher what you're doing. > > Only an expert like you could come up with something that clever! ------------------- Actually wait, I just realized, after finally figuring out what these codes do, that these are just more clever ways of solving my problem, that avoid doing the loops over many variables. As I said before, this problem of generating all permutations with repetition was already solved by Matt Fig's npermutek.m [ a=npermutek(1:k,n) does the trick ] What I really wanted to know was if there was a way to loop over an array of variables like: ------------------- for a=1:5; for b=1:5; for c=1:5; % for d=... for e=... answer=a+b+c+ ... ; end end end end ... ------------------- But without typing all of those for's and end's. So something like: ------------------- indices={'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o'}; for y=1:length(indices) for (indices{y})=1:5 answer=indices{1}+indices{2}+indices{3} ... ; end end ------------------- I'm not asking for a way to solve the problem of a+b+c ... more cleverly, I'm just asking if there's a way to loop over all these different variables without typing them out individually. a+b+c .. was just a simple example to replace the big subroutine that I'm putting there. Is the only way to do this by using the eval command and "poofing" variables into existence ?? Thanks where at each |