COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### forloop within statements

• Email
• Follow

```In Maple we can do things like:

M( for i=1:3; i^2 ; end , 3)

to get:

M(1,3)
M(4,3)
M(9,3)

By defining 'procedures' within the statements

================
================

My goal is to be able to do something similar in matlab:

I =
[ 1     1     1 ;
1     1     2 ;
1     2     1 ;
1     2     2 ;
2     1     1 ;
2     1     2 ;
2     2     1 ;
2     2     2 ]

indices =
[     1     1     1 ;
1     2     1 ;
2     2     1 ;
2     2     2 ]

I want to get the 'indices' array, from 'I' :

I((indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0,:)

1     1     1
1     2     1
2     2     1
2     2     2

=============

Of course, when there's more columns it would be nice to be able to do:

I( sum_from_i=1:n (indices(:,i)-1)*2^i   ,:)

[this type of summation is very commonly applied  within arguments in Maple]

Is this possible in matlab ?

I was trying it with arrayfun and cumsum, but couldn't get anywhere
```
 0

See related articles to this posting

```I'm aware that I could of course save:

J=0;
for i=0:n
J=J+(indices(:,1)-i)*2^i
end

and then do I(J,:)

but since the arrays I'm dealing with are so big, I'm worried that saving J separately might use up all my memory.

Since I don't need to save J, I thought that doing the forloop within the argument of the array would save memory (although perhaps the same amount of memory is being allocated to ANS ... I'm not sure)
```
 0

```I'm terribly sorry, but in my examples I made some silly mistakes:

in my first post I  meant that I want to do:
I( sum_from_i=0:n (indices(:,n-1-i)-1)*2^i ,:)

In the last one I meant to say:

for i=0:n
J=J+(indices(:,n-1-i)-1)*2^i
end

Thanks for bearing with my idiocy.
```
 0

```Of course your 'I' array does not have 9 rows, so the example is a little off.  Still, one can do:

% Given the array 'I':
I = magic(9);

% Get the 'indices' array from 'I' (as you stated)
indices = I((1:3).^2,:)
```
 0

```I'm terribly sorry, but in my examples I made some silly mistakes:

in my first post I  meant that I want to do:
I( sum_from_i=0:n (indices(:,n-1-i)-1)*2^i ,:)

In the last one I meant to say:

for i=0:n
J=J+(indices(:,n-1-i)-1)*2^i
end

Thanks for bearing with my idiocy.
```
 0

```Something is not clear.

First you say you want to be able to get 'indices' from 'I', then you show an example of where you are getting 'J' from both 'indices' and 'I'.  So which is it?  Are you given 'I' and 'indices' and need to get 'J', or what???
```
 0

```"Matt Fig" <spamanon@yahoo.com> wrote in message <hrnb7g\$hts\$1@fred.mathworks.com>...
> Something is not clear.
>
> First you say you want to be able to get 'indices' from 'I', then you show an example of where you are getting 'J' from both 'indices' and 'I'.  So which is it?  Are you given 'I' and 'indices' and need to get 'J', or what???

I have 'I' and 'indices':

I =
[ 1 1 1 ;
1 1 2 ;
1 2 1 ;
1 2 2 ;
2 1 1 ;
2 1 2 ;
2 2 1 ;
2 2 2 ]

indices =
[ 1 1 1 ;
1 2 1 ;
2 2 1 ;
2 2 2 ]

I want to get the 'indices' array, from 'I' .

One way I can do this is:

I((indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0,:)

In that solution we have the rather complicated argument,
J=(indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0

So

I(J,:)

Now J should actually be calculated in a loop rather than typed out in full (to generalize for arrays with more than 3 columns).

J could be calculated in a loop *before* being called as the row of 'I' :

That's what the second example demonstrated.

But doing that requires me to store J, which will take up too much memory.

The example
I((1:3).^2,:),

only gives me the first 3 rows of 'I' rather than the 1st, 3rd, 7th and 8th (which is what my first example gives).

*I hope this makes sense! =)
```
 0

```"Juliette Salexa" <juliette.physicist@gmail.com> wrote in message
> I have 'I' and 'indices':
>
> I =
>    [ 1 1 1 ;
>      1 1 2 ;
>      1 2 1 ;
>      1 2 2 ;
>      2 1 1 ;
>      2 1 2 ;
>      2 2 1 ;
>      2 2 2 ]
>
> indices =
> [ 1 1 1 ;
>       1 2 1 ;
>       2 2 1 ;
>       2 2 2 ]
>
> I want to get the 'indices' array, from 'I' .

O.K.,  You already have both 'I' and 'indices', but you want to get 'indeces' from 'I'.  Why anyone would want to do such a thing is beyond me, but this will work:

indices = I(ismember(I,indices,'rows'),:)
```
 0

```Juliette Salexa wrote:
> In Maple we can do things like:
>
> M( for i=1:3; i^2 ; end , 3)
>
> to get:
>
> M(1,3)
> M(4,3)
> M(9,3)
>
> By defining 'procedures' within the statements

No, you cannot. 'for' is a statement in Maple, not an expression. The closest
expression equivalents in Maple to what you are showing are the \$
(dollar-sign) operator, and the seq() built-in routine.

In Maple, both \$ and seq() form Maple "expression lists", which are fairly
similar to de-indexing a cell array in a Matlab expression, such as

>> C=num2cell((1:3).^2);   %matlab code
>> M(C{:}, 3)

This would, in Matlab, be as-if you had written

M(1, 4, 9, 3)

which would be either a 4-dimensional matrix index or 4 arguments to a
procedure. Just so, in Maple:

> M(i^2\$i=1..3, 5);       #Maple code
M(1, 4, 9, 5)
> M(seq(i^2,i=1..3),3);   #Maple code
M(1, 4, 9, 3)

To do what you are suggesting, the closest Maple would be:

> M(i^2,3)\$i=1..3;        #Maple code
M(1, 3), M(4, 3), M(9, 3)

or

> seq(M(i^2,3),i=1..3);   #Maple code
M(1, 3), M(4, 3), M(9, 3)

Maple's Matrix and Array and Vector data types (the rtable based datatypes)
support ranges as indices, such as M[1..3,2] but those are handled by the
rtable indexing facility, not as a general case in Maple.

> My goal is to be able to do something similar in matlab:

> I want to get the 'indices' array, from 'I' :

> I((indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0,:)

> Of course, when there's more columns it would be nice to be able to do:

> I( sum_from_i=1:n (indices(:,i)-1)*2^i   ,:)

>> I(1 + (indices-1) * 2.^[size(indices,2)-1:-1:0].',:)
ans =
1     1     1
1     2     1
2     2     1
2     2     2

If I were using this regularly I would probably define an anonymous function
for it:

B2 = @(indices) 1 + (indices-1) * 2.^[size(indices,2)-1:-1:0].';

I(B2(indices), :);

> [this type of summation is very commonly applied  within arguments in
> Maple]

I've done a fair bit of Maple, but I rarely see what you are describing being
used. I _have_ seen my share of seq() and of \$ and of map(). It is also not
too uncommon to see computing of indices such as in

M[[i^2\$i=1..3],2];           #Maple code

However, Maple code written with generalization in mind would not rely on a
list in an indexing position implying indexing at each of the entries of the
list, as that indexing construct does not work for lists or sets, or for data
of type array (lower-case 'A') or matrix (lower-case 'M') or vector
(lower-case 'V') [that is, the older table-based data-types to the newer
rtable-based data-types that have the capital letters.] Now, it is true that
in some of my Maple code, I have used convert() to ensure that the values are
in Array data type for efficiency, but in those routines to the extent that it
made sense to do so, I kept track of the input data type and converted back to
that data type before returning the value to the user.
```
 0

```"Juliette Salexa"
> One way I can do this is:
> I((indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0,:)

this is all too confusing...
why is there no -1 in the last INDICES() term(?)...
this does not correspond to an earlier post, where you state

for  i=0:n
J=J+(indices(:,n-1-i)-1)*2^i
end

?????
us
```
 0

```Walter Roberson <roberson@hushmail.com> wrote in message

> I(1 + (indices-1) * 2.^[size(indices,2)-1:-1:0].',:)

Perfect! This works, although I'll have to think about it some more to figure out how the forloop is being done implicitly, and how to generalize this to perform more general forloops within more general statements
============================================

> No, you cannot. 'for' is a statement in Maple, not an expression.

To illustrate what I wanted to do in matlab, I wanted to give the maple examples:

H = Matrix(2, 2, [[1, 2], [3, 4]]);
G = Matrix(2, 2, proc (i, j) H(i, j) end proc);  # FOR LOOP WITHIN STATEMENT

a := b[i]^2;
sum(a, b[i] = 1 .. 2); # FOR LOOP WITHIN STATEMENT

But in case there's not many Maple users here, I just said
"Maple can do things like M( for i=1:3; i^2 ; end , 3)"

By that, I meant that you can 'effectively' do a forloop within a statement, not that the syntax I used is actually a valid Maple command =) *sorry for the confusion*
============================================

Also, thanks for showing me the \$ command - I haven't seen it before but it looks like it will be useful!
============================================

"Matt Fig" <spamanon@yahoo.com> wrote in message

> O.K.,  You already have both 'I' and 'indices', but you want to get 'indeces' from 'I'.  Why anyone would want to do such a thing is beyond me, but this will work:
>
> indices = I(ismember(I,indices,'rows'),:)

The reason why I wanted to be able to get 'indices' from 'I' ... was because if based on the information in 'indices' , I could figure out where the rows of 'indices' are in 'I' ... then if I have g=rand(size(I)), I can get the corresponding rows of g. In the above example, since indices==I([1 3  7 8],:) , I would want g([1 3 7 8]).

The simplest way I could think of doing this was

I((indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0,:)

And therefore my real question was how to do that without having to write indices(:,~)  N times.

Thanks so much both Walter and Matt Fig
```
 0

```"us " <us@neurol.unizh.ch> wrote in message <hrnk0n\$ja7\$1@fred.mathworks.com>...

> > I((indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0,:)
>
> why is there no -1 in the last INDICES() term(?)...

That's a very good question.

If there was a "-1" in the last term, that line would obviously not give me the right result,

Therefore, my forloop would need to address the first n-1 terms, and the n'th term would be added separately (with no -1 involved).

Thank you very much for pointing that out.

Based on all this, I guess there's no way to embed forloops into statements in matlab the way we can (effectively) in maple ...
```
 0

```Juliette Salexa wrote:

> H = Matrix(2, 2, [[1, 2], [3, 4]]);
> G = Matrix(2, 2, proc (i, j) H(i, j) end proc);  # FOR LOOP WITHIN
> STATEMENT

Providing a procedure that generates the values to be inserted into a Matrix
is handled as a special case in the code that decides what initial value
should go where in the Matrix. There isn't really a 'for' loop in the Maple
statement that you marked. The Maple routine Matrix will take the procedure
and pass it down to the low-level built-in routine rtable() that does the hard
work; that routine will call the procedure repeatedly over the necessary
subscript lists. As this is a two dimension Matrix being constructed,
logically a doublely-nested for loop would be used

> a := b[i]^2;
> sum(a, b[i] = 1 .. 2); # FOR LOOP WITHIN STATEMENT

Maple's sum() is actually a pretty complex function intended to do symbolic
summation over indices that are variables. If you provide specific endpoints
for the summation, Maple's sum() routine will first calculate the closed-form
of the summation (if it can) and then will substitute the specific endpoints
into the closed formula. If sum() cannot find a closed form for the summation,
it will return unevaluated, even if you supply specific endpoints, unless the
endpoints are less than 10000 apart (if they are, it will construct the
sequence of expressions and do routine constant collection on it.)

When you do not want to do a symbolic summation in Maple, when you just want
rewritten as

which means "let i range over all of the elements in a and add those values
all up" -- and would apply even if the array was multidimensional. The
corresponding code in Matlab would be close to

sum(a(:));     #Matlab code

> By that, I meant that you can 'effectively' do a forloop within a statement

Matlab has its colon operator, which does not actually expand to the list of
numbers if it is seen in the limits for a 'for' loop, or if the entire range
is being specified for a subscript reference by coding a simple ':' . There
may be other optimized cases that I am not aware of.

Maple has a range constructor that is, in itself, inert: for example, where in
Matlab, 1:5 would expand to the row vector [1, 2, 3, 4, 5], the corresponding
Maple syntax, 1..5, is transformed into a symbolic function call to the `..`
function, with first argument 1 and second argument 5 -- and that is how it
would be passed around, symbolically, unless there happens to be a call in the
code that needs to expand it. The normal Maple operations such as sum() and
add() and int() [integration] do not generate the actual list of numbers: they
infer the values in internal for loops.

> Also, thanks for showing me the \$ command

No problem.

Do note, though, that sometimes in Maple it is better to avoid using the \$
operator. For example, if you have

seq(f(x), x=[\$1..5]);

then Maple will evaluate the \$1..5 to the expression sequence 1, 2, 3, 4, 5
and then wrap a list around it because of the [], and that list will become
the value that x is iterated over by the seq() command. If, though, you had used

seq(f(x), x=1..5);

then maple will construct the symbolic object `..`(1,5) and seq() will example
that symbolic value and will iterate over the required values, without ever
constructing an explicit list of values to iterate over.

One way or another, the \$ operator in Maple results in an expression list
actually being created, whereas the Maple range constructor, .. (two periods)
can often avoid building a a real expression list.

Urrr, what can I say? I got my Maple 14 license the day after the product
release announcement ;-)
```
 0

```> Walter Roberson <roberson@hushmail.com> wrote in message

I agree that my Maple examples weren't genuine forloops, but my point was that Maple allows you to specify index variables for iterative calculations *within* statements, which is effectively performing a forloop within a statement. I was wondering whether or not matlab had this capability, and your suggestion:

> sum(a(:));     #Matlab code
>

demonstrates that matlab does indeed have this capability (at least for the specific case of iteratively specifying indices) !

I((indices(:,a(:))-1)*2.^flipud(a(:))+indices(:,end)*2^0,:)

gives the exact same result as:

K((indices(:,1)-1)*2^2+(indices(:,2)-1)*2^1+indices(:,3)*2^0,:)

EXCELLENT ! =)

> Urrr, what can I say? I got my Maple 14 license the day after the product
> release announcement ;-)

I can see you that you know a lot of Maple.

I began with Maple too, but had to learn mathematica when I changed workplaces since no one here knows Maple. A recent survey showed that about twice as many people use mathematica as maple, and I think the difference in the number of users will  just get bigger and bigger over time, because of things like:

(1) Almost everyone's going to use Wolfram Alpha at some point (especially high school students that are checking their math homework). And lots of people will already know mathematica, but not maple. Wolfram Alpha is useful for quite a lot of stuff, here's the demo:
http://www.wolframalpha.com/screencast/introducingwolframalpha.html

(2) Mathworld pages now allow you to download the mathematica notebook files that were used to produce them ... so for example, if you go to mathworld to learn what a fourier transform is, you already know how to do almost everything fourier transform related in mathematica, but not necessarily in maple,

see the download button which is at the top of most mathworld pages: http://mathworld.wolfram.com/FourierTransform.html

(3) Examples of how to do almost anything that has already been coded by another mathematica user are available either in the Wolfram Demonstrations Project

http://demonstrations.wolfram.com/topics.html#5

or WebMathematica:

http://www.wolfram.com/products/webmathematica/examples/examples.html

So it's very easy for high school students to get used to mathematica very quickly.

======

All that being said, I'm still a Maple user and know Maple much much much better than Mathematica, so I hope MapleSoft's Marketing team turns around and prevents Maple from becoming the obsolete language that no one uses in 2050, like ShortCode became when FORTRAN took over (or something to that effect)
```
 0

```Juliette Salexa wrote:

> I began with Maple too, but had to learn mathematica when I changed
> workplaces since no one here knows Maple. A recent survey showed that
> about twice as many people use mathematica as maple, and I think the
> difference in the number of users will  just get bigger and bigger over
> time,

I have used both, though it has been probably more than a decade since I
used Mathematica for anything non-trivial. There were a fair number of
things that were easier in Mathematica or better designed (e.g., major
differences in graphics flexibility) -- but at least at the time, I was
finding too many situations in which Mathematica was unable to solve or
reasonably simplify the expressions I was working with, but Maple had no
trouble with them. It was wasting my time to keep hitting limitations in
the then-Mathematica, so I switched over to Maple as my primary package.
I know that Mathematica has improved quite a bit since that time, but I
never had reason to switch back.

There is something about Maple that brings out the hacker in me, the
urge to find clever ways to do things -- sort of similar to the way that
people posting here often aim for one-line solutions for their postings,
even if they would never actually use such code in their production
programs. And I hunt around and experiment and see how I can push the
boundaries of Maple, just to see what happens; I never developed that
urge with Mathematica.

Anyhow... I'd better get moving!
```
 0