Retrieving element index in spfun, cellfun, arrayfun, etc. in MATLAB

后端 未结 3 1646
情书的邮戳
情书的邮戳 2021-02-07 13:06

Is there any way to retrieve the index of the element on which a function called by cellfun, arrayfun or spfun acts? (i.e

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 13:40

    No, but you can supply the linear index as extra argument.

    Both cellfun and arrayfun accept multiple input arrays. Thus, with e.g. arrayfun, you can write

    a = [1 1 2 2];
    lin_idx = 1:4;
    out = arrayfun(@(x,y)x*y,a,lin_idx);
    

    This doesn't work with spfun, unfortunately, since it only accepts a single input (the sparse array).

    You can possibly use arrayfun instead, like so:

    S = spdiags([1:4]',0,4,4);
    lin_idx = find(S);
    
    out = spones(S);
    out(lin_idx) = arrayfun(@(x,y)x*y,full(S(lin_idx)),lin_idx);
    %# or
    out(lin_idx) = S(lin_idx) .* lin_idx;
    

    Note that the call to full won't get you into memory trouble, since S(lin_idx) is 0% sparse.

提交回复
热议问题