Verify a matrix value on MATLAB

前端 未结 3 1124
醉话见心
醉话见心 2021-01-22 05:41

I am using MATLAB. I have a question about how i can verify that the values of a matrix are being repeating, like this:

A=[ 2 3 2 3 2 3 2 3]

If

相关标签:
3条回答
  • 2021-01-22 06:17

    The following one-liner works if A is a row or column vector, but not necessarily if it is a matrix (thanks to @Dan for providing a simplification in comments). I figured this would be okay since the example you provide in the question is a vector.

    AUX = ~any(A(3:end) - A(1:end-2))
    

    This vectorized solution should be a lot faster than the non-vectorized solution supplied by @Nirk (for large A).

    Depending on your application you may need to include the error trap:

    if size(A, 2) < 3; error('Input matrix needs to have at least 3 columns'); end
    

    Note, see the comments on this answer for some alternative ways of dealing with the case size(A, 2) < 3.

    0 讨论(0)
  • 2021-01-22 06:20

    Here is another simple way to do it:

    AUX = all(A(1) == A(1:2:end)) && all(A(2) == A(2:2:end))
    

    Basically this checks whether all odd elements are equal to the first element, and all even elements are equal to the second element.

    0 讨论(0)
  • 2021-01-22 06:29

    I would like to throw in another approach. As I see when you are asking for "repetion" so maybe you want to have the same "pattern" repeated. For this it's easy to abuse the string functions.

    A=[1,2,3,4,1,2,3,4,1,2,3]
    position_repetition = strfind(A,A(1:2))
    

    I suppose you could use regexp for more complicated pattern. Like this would check for the longest pattern that is repeated:

    tmp = regexp(char(A),'(?<group>.+)\1+','names')
    group = double(tmp.group)
    

    this should be as I understand the question - it checks if it is a repetion of the first two entries:

    A=[1,2,3,4,1,2,3,4,1,2,3,4]
    tmp = regexp(char(A),'^(?<group>..)\1+$','names')
    AUX = ~isempty(tmp)
    
    0 讨论(0)
提交回复
热议问题