How to compare array to a number for if statement?

前端 未结 3 1971
礼貌的吻别
礼貌的吻别 2020-12-11 03:30

H0 is an array ([1:10]), and H is a single number (5).

How to compare every element in H0 with the s

3条回答
  •  独厮守ぢ
    2020-12-11 03:40

    Anyway take a look at this: using ismemeber() function. Frankly not sure how do you expect to compare. Either greater than, smaller , equal or within as a member. So my answer might not be yet satisfying to you. But just giving you an idea anyway.

    H0 = [0 2 4 6 8 10 12 14 16 18 20];
    H  = [10];
    ismember(H,H0)
    IF (ans = 1) then
    // true
    else
    //false
    end 
    

    Update Answer

    This is super bruteforce method - just use it explain. You are better off with any other answers given here than what I present. Ideally what you need is to rip off greater/lower values into two different vectors with ^3 processing - I assume... :)

    H0 = [0 2 4 6 8 10 12 14 16 18 20];
    H  = [10];
    
    H0(:)
    ans = 
         0
         2
         4
         6
         8
         10
         12
         14
         16
         18
         20
    

    Function find returns indices of all values in H0 greater than 10 values in a linear index.

    X = find(H0>H)
    X = 
         7
         8
         9
         10
         11
    

    Function find returns indices of all values in H0 lower than 10 in a linear index.

    Y = find(H0

    If you want you can access each element of H0 to check greater/lower values or you can use the above matrices with indices to rip the values off H0 into two different arrays with the arithmetic operations.

    G = zeros(size(X)); // matrix with the size = number of values greater than H
    J = zeros(size(Y)); // matrix with the size = number of values lower than H
    
    for i = 1:numel(X)
         G(i) = H0(X(i)).^3
    end
    
    G(:)
    ans =
    
          1728
          2744
          4096
          5832
          8000
    
    for i = 1:numel(Y)
         J(i) = H0(Y(i)).^2
    end
    
    J(:)
    ans =
    
          0
          4
         16
         36
         64
        100
    

提交回复
热议问题