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

后端 未结 3 1645
情书的邮戳
情书的邮戳 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:22

    It's simple. Just make a cell like: C = num2cell(1:length(S)); then: out=arrayfun(@(x,c) c*x,S,C)

    0 讨论(0)
  • 2021-02-07 13:24

    You can create a sparse matrix with linear_index filling instead of values.

    Create A:

    A(find(S))=find(S)
    

    Then use A and S without spfun, e.g.: A.*S. This runs very fast.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题