For Programmers: Free Programming Magazines  


Home > Archive > Matlab > September 2006 > alternating sweeps









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author alternating sweeps
bcirhelp

2006-09-23, 4:07 am

I need help with writing the following code so it is not redundant. I need to execute the following code:

for i=n+1:-1:1
statement...

for j=1:n+1
statement...
end
end

an additional three times but with direction for i and j changing as follows:

i=n+1:-1:1
j=n+1:-1:1

i=1:n+1
j=n+1:-1:1

i=1:n+1
j=1:n+1

The code remains the same with only the direction of i and j changing. Thank you
Rune Allnor

2006-09-23, 4:07 am


bcirhelp skrev:
> I need help with writing the following code so it is not redundant.


Homework?

Rune

John D'Errico

2006-09-23, 4:07 am

In article <7805808.1158987154675.JavaMail.jakarta@nitrogen.mathforum.org>, bcirhelp <lionatucla@verizon.net> wrote:

> I need help with writing the following code so it is not redundant. I need
> to execute the following code:
>
> for i=n+1:-1:1
> statement...
>
> for j=1:n+1
> statement...
> end
> end
>
> an additional three times but with direction for i and j changing as follows:
>
> i=n+1:-1:1
> j=n+1:-1:1
>
> i=1:n+1
> j=n+1:-1:1
>
> i=1:n+1
> j=1:n+1
>
> The code remains the same with only the direction of i and j changing. Thank
> you


Rune asks (very possibly correct) if this
is homework. So I won't do it for you
directly.

But why not just do it all in the one
double loop? Is there a law that says you
cannot put multiple statements inside your
loops?

Even better, why not just do it once in a
vectorized fashion using meshgrid? This
actually would use the capabilities of
matlab.

HTH,
John D'Errico


--
The best material model of a cat is another, or preferably the same, cat.
A. Rosenblueth, Philosophy of Science, 1945

Those who can't laugh at themselves leave the job to others.
Anonymous
us

2006-09-23, 8:05 am

bcirhelp:
<SNIP dynamic for loop...

one of the many solutions, which easily could be wrapped into a
function, is outlined below
us

% the templates
n=3;
ixt1=n+1:-1:1;
ixt2=1:n+1;
ix={
ixt1 ixt2
ixt1 ixt2
ixt2 ixt1
ixt2 ixt2
};
% the engine
for t=1:size(ix,1)
for i=ix{t,1}
for j=ix{t,2}
% a simple statement
disp(sprintf('run %1d i=%2d j=%2d',t,i,j));
end
end
end
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com