检查真正的正整数

时间:2016-08-14 18:49:47

标签: matlab

如何改进(缩短)我的检查值是真正的正整数?我想先做一个整数(a),我试过

 a~=floor(a) || a<=0 || imag(a)~=0 

其次,我想为链表做这件事

l=struct('xpos',value,'ypos',value,'entry',value,'next',[])
l=struct('xpos',value,'ypos',value,'entry',value,'next',l)

等等。

对于列表我希望所有xpos和ypos值都是实数正整数,我试过

 any(l.xpos~=floor(a) || l.xpos<=0 || imag(l.xpos)~=0 || l.ypos~=floor(l.ypos) || l.ypos<=0 || imag(l.ypos)~=0)

当我有两个要检查的列表时,这最终会很长。

1 个答案:

答案 0 :(得分:0)

您可以简化检查并使用以下内容将其转换为匿名函数:

isPositiveInt = @(x)isscalar(x) && isnumeric(x) && abs(round(x)) == x && x > 0;

如果确保它始终是标量和数字,您可以将其简化为:

isPositiveInt = @(x)abs(round(x)) == x && x > 0;

然后,您可以轻松地对xposypos

执行此检查
isPositiveInt(S.xpos) && isPositiveInt(S.ypos)

要浏览“链接列表”,您只需要循环播放

while ~isempty(S)
    % They they are both integers do something
    if isPositiveInt(S.xpos) && isPositiveInt(S.ypos)
        % Do something
    end

    % Go onto the next one
    S = S.next;
end

作为旁注,最好避免使用小写l作为变量,因为它看起来很像1。在上面的示例中,我已将其切换为S

相关问题