matlab 动态指定输出数量

58wvjzkj  于 7个月前  发布在  Matlab
关注(0)|答案(1)|浏览(78)

numpy.where类似于ind2sub

[i1, i2, ..., i<ndims(x)>] = ind2sub(size(x), find(x > 0));

除了np.where返回一个i1i2,.的元组,它们本身就是数组(所以我们可以只做out = np.where())。
这个想法是,np.where不需要担心知道ndims(x)。有没有办法用MATLAB做同样的事情?我在下面思考:

out = cell(1, ndims(x));
out{:} = ind2sub(size(x), find(x > 0));  % DOESN'T WORK

更一般地说:我们可以在MATLAB函数上强制使用nargout,而不需要输入nargout变量吗?
我当前的np.where端口将在自定义函数中简单地使用switch ndims(x)

function out = np_where(bools, sz)
    switch numel(sz)
        case 1
            i1 = ind2sub(sz, bools);
            out = {i1};
        case 2
            [i1, i2] = ind2sub(sz, bools);
            out = {i1, i2};
        % ...
pcrecxhr

pcrecxhr1#

你需要在你的comma-separated list周围使用方括号,当你说out{:}时就形成了方括号。

x = randi([-1 1],2,2,2,2);
out = cell(1, ndims(x));
[out{:}] = ind2sub(size(x), find(x > 0));

相关问题