Matlab比较中的一个错误?

时间:2016-03-29 00:44:41

标签: matlab comparison

我在Matlab中编写自己的版本ismemberfind_element),通过比较a来检查矩阵b中是否有行数组ab中的每一行。如果a中的每个元素都等于' b中每行的每个元素(如果绝对错误小于Tol),则返回逻辑值1和行号。

然而,当我测试我的代码时,我发现当将t=[1 1]a=1.0e-11*[0.9063 0.0838]进行比较时,Matlab将返回B=[-1 0]Bb的第二行})。实际上它提供了正确的绝对错误error=[1.0000 0.0000],并且显然error(1)大于Tol=1e-6。我在Matlab中发现了一个错误吗?或者我的代码中有错误吗?

以下是我的find_element代码:

function [Lia,Locb] = find_element(a,b)
%decide whether a is in b or not(compare each row); if in, return row number
%INPUT:
%a: salar or row array
%b: column array or matrix 
%OUTPUT:
%Lia: 1 if a is in b, 0 if not
%Locb: location of a in b, row number if b is a matrix
Tol = 1e-6; %set tolerance when compare elements
Lia = 0;%initialization
Locb = 0;

t = zeros(size(a));%compare result of each element,logical array
for i = 1:size(b,1) %loop through each row
    for j = 1:size(b,2) %compare each element in each row
        if abs(a(j)-b(i,j))<Tol
            t(j) = 1;
        end
    end
    if t %all 1's
        Lia = 1;%find a in b
        Locb = i;%return row number
        %%%%%%%%%%%%%%%%%%%%%%%%
        %test outputs
        a
        B=b(i,:)
        error = abs(a-b(i,:))
        t
        %%%%%%%%%%%%%%%%%%%%%%%%
        break
    end
end

测试代码是:

a = [9.06319429228031e-12   8.37879678833309e-13];
b = [0 1;-1 0;1 0;0 1];
[Lia Locb] = find_element(a,b)

输出是:

a =
   1.0e-11 *
    0.9063    0.0838
B =
    -1     0
error =
    1.0000    0.0000
t =
     1     1
Lia =
     1
Locb =
     2

2 个答案:

答案 0 :(得分:0)

#转换为%后,我发现您的代码在Matlab中适用于以下示例。如果您的问题出现在Octave中,请提供清晰可重复的答案或编辑您的问题。

>> a=1.0e-11*[0.9063 0.0838];
>> b=[-1 0];
>> [Lia, Locb] = find_element(a,b)

Lia =

     0


Locb =

     0

>> [Lia, Locb] = find_element([-1.000001 0],b)

a =

           -1            0


B =

    -1     0


error =

        1e-06            0


t =

     1     1


Lia =

     1


Locb =

     1

答案 1 :(得分:0)

我现在在代码中发现问题:t需要在检查每一行之前进行初始化。通过将t = zeros(size(a))放在i循环中,它现在可以正常工作。

...
for i = 1:size(b,1) %loop through each row
    t = zeros(size(a));%compare result of each element,logical array
    for j = 1:size(b,2) %compare each element in each row
....

测试和输出:

>> a = [9.06319429228031e-12    8.37879678833309e-13];
>> b = [0 1;-1 0;1 0;0 1];
>> [Lia Locb] = find_element(a,b)

Lia =

     0


Locb =

     0