You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MATLAB中实现类似numpy.where的动态输出数量功能?

实现类似numpy.where的MATLAB函数

功能对比

numpy.where 的功能和 MATLAB 中的 ind2sub 类似,MATLAB 中通常通过以下代码实现类似逻辑:

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

两者的区别在于:np.where 会直接返回一个包含 i1、i2 等各维度索引数组的元组,只需执行 out = np.where() 就能一次性获取所有结果。

核心问题

np.where 不需要提前知晓输入数组的维度数 ndims(x),那在 MATLAB 中能否实现同样的效果?我尝试了以下代码,但无法运行:

out = cell(1, ndims(x));
out{:} = ind2sub(size(x), find(x > 0));  % 无法运行

更宽泛地说:在MATLAB中能否通过编程方式为函数指定nargout,无需手动写出对应数量的接收变量?

临时解决方案

目前我移植 np.where 的方法是在自定义函数中通过 switch 分支处理不同维度的情况:

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};
        % ... 需继续添加更高维度的分支

内容的提问来源于stack exchange,提问作者OverLordGoldDragon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 20:57:49