【问题标题】:function that takes a vector and returns negative numbers and position接受向量并返回负数和位置的函数
【发布时间】:2017-03-13 03:36:12
【问题描述】:

我正在寻找创建一个函数,该函数将接受一个向量并返回一个向量中的所有负值及其在另一个向量中的位置。所以,例如,

% output:
v = [-1 4 6 2 -3]

% output:
vneg = [-1 -3]
pos  = [1 5].

感谢任何帮助!

【问题讨论】:

    标签: matlab function vector


    【解决方案1】:

    获取负值及其索引的简单解决方案。

    x = [4 3 -2 9 -7 31];
    
    index = find(x<0);
    -> index = 3 5
    
    x_new = x(index);
    -> x_new = -2 -7
    

    只需根据您的要求更改查找功能中的条件。

    【讨论】:

    • 感谢您的帮助,但我如何在函数中编写它?我相信我需要使用循环
    • 你需要学习一下。了解 find() 函数在 matlab 中的作用。你会得到答案的。
    【解决方案2】:

    只是为了完成@WasiAhmad 的回答:

    function [vneg, pos] = find_negatives(V)
    
        pos  = find(V < 0);
        vneg = V(pos);
    
    end
    

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 2020-08-05
      • 2021-03-23
      • 1970-01-01
      • 2018-06-12
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多