help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Disaggregating input arguments for sub2ind


From: Juan Pablo Carbajal
Subject: Re: Disaggregating input arguments for sub2ind
Date: Thu, 20 Feb 2014 23:12:59 +0100

On Thu, Feb 20, 2014 at 10:46 PM, Alexander Barth
<address@hidden> wrote:
>
> On Wed, Feb 19, 2014 at 3:39 PM, Juan Pablo Carbajal <address@hidden>
> wrote:
>>
>> On Wed, Feb 19, 2014 at 2:38 PM, Nir Krakauer <address@hidden>
>> wrote:
>> > Dear all,
>> >
>> > I have an n-D grid whose size is given by grid_size, and an array of
>> > subscripts with size npoints*ndims, for example:
>> >
>> > grid_size = [5 4];
>> > grid_subs = [1 4; 5 1; 3 2];
>> >
>> > What's a general way to convert the subscripts to single indices,
>> > achieving
>> > the same result as, for example,
>> > grid_inds = sub2ind (grid_size, grid_subs(:, 1), grid_subs(:, 2)); #2-D
>> > case
>> > grid_inds = sub2ind (grid_size, grid_subs(:, 1), grid_subs(:, 2),
>> > grid_subs(:, 3)); #3-D case
>> > if the number of dimensions in the grid may vary between calls?
>> >
>> > Nir
>> >
>> > _______________________________________________
>> > Help-octave mailing list
>> > address@hidden
>> > https://mailman.cae.wisc.edu/listinfo/help-octave
>> >
>>
>> Nir,
>>
>> Besides having  eval statement with the parametrized string, I
>> wouldn't know any other way, since it seems sub2ind doesn't accept
>> zipped arguments... something like the **kargs in python.
>> I hope Jordi corrects me on this.
>
>
> Dear Nir,
>
> You can, but you have to use cell arrays for the indices. For example:
>>> A = magic(5)
> A =
>
>    17   24    1    8   15
>    23    5    7   14   16
>     4    6   13   20   22
>    10   12   19   21    3
>    11   18   25    2    9
>
>
>>> ind = {2,3}
> ind =
> {
>   [1,1] =  2
>   [1,2] =  3
> }
>
> Elements of ind can also be vectors (e.g. ind = {[ 2 3],[3 3]} as in your
> question)
>
>>> lindex = sub2ind(size(A),ind{:})
> lindex =  12
>>> A(lindex)
> ans =  7
>>> A(2,3)
> ans =  7
>
> If you want to access the corresponding element in A you can use directly
> this:
>
>>> A(ind{:})
> ans =  7
>
> As indexing calls the method subsref, one could also use this subsref(A,idx)
> where idx = substruct ('()',ind), but I found the the previous method is
> much faster.
>
> To use ind2sub, you can use this:
> ind = cell(ndims(A),1);
> [ind{:}] = ind2sub(size(A),lindex)
>
>
> In my package divand, I had to use such constructs to make the code work in
> an arbitrary number of dimensions.
>
>
> Regards,
> Alexander
>
>
>
>>
>> _______________________________________________
>> Help-octave mailing list
>> address@hidden
>> https://mailman.cae.wisc.edu/listinfo/help-octave
>
>

Plus to that...we should have it in the cookbook
http://wiki.octave.org/Cookbook


reply via email to

[Prev in Thread] Current Thread [Next in Thread]