Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: creating loops for a large system of variables
Date: Sun, 3 Apr 2011 19:50:05 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 55
Message-ID: <inaj1d$j5b$1@fred.mathworks.com>
References: <ina9ds$qcn$1@fred.mathworks.com> <inab9s$o34$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-03-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1301860205 19627 172.30.248.48 (3 Apr 2011 19:50:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 3 Apr 2011 19:50:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 2408071
Xref: news.mathworks.com comp.soft-sys.matlab:719809

>   That would not only be a lot of wasted time on for-loops, it would be an awful lot of additions, never mind the for-loops!  If each of a thousand variables were to independently vary over just two numbers, the number of necessary additions would exceed the famous "googol" of Edward Kasner fame.  There aren't that many atoms in the known universe.
> 
> Roger Stafford

Well, I worked something out, and I guess I'll find out later if it's worth it, but basically this code writes a new code which wraps for loops around a function depending on the length of the variables.  If a variable is of length 1, then no for loop is written, but if the variable is of length 2 or greater, then a for loop is wrapped around the function.

In case anyone is interested, here is the code:

clear all
close all

a = 1;
b = [1 2];
c = 1;

s = whos;

fname = 'myfun';

datenow = datestr(now, 'mm-dd-yy HH-MM-SS');

fid = fopen(['temp ' datenow '.m'], 'w');

iteration = cell(length(s),1);
for ii = 1:length(s)
    if s(ii,1).size(2) == 1
        iteration{ii} = ',';
    else
        str = ['for ', s(ii,1).name, 'loop = 1:length(', s(ii,1).name, ')'];
        fprintf(fid,'%s\n',str);
        iteration{ii} = ['(',s(ii,1).name, 'loop),'];
    end
end

str = [fname, '('];
fprintf(fid,'%s',str);
for ii = 1:length(s)
    if ii == length(s)
        str = [s(ii,1).name iteration{ii}(1:end-1)];
        fprintf(fid,'%s',str);
    else
        str = [s(ii,1).name iteration{ii}];
        fprintf(fid,'%s',str);
    end
end
fprintf(fid,'%s\n',')');

for ii = length(s):-1:1
    if s(ii,1).size(2) == 2
        str = 'end';
        fprintf(fid,'%s\n',str);
    end
end

fclose(fid);