简体   繁体   中英

Compare Values in Array on Specific Indexes in Matlab

how to Compare Values in Array on Specific Indexes in Matlab? Suppose:

A= [2 2 3 3 3  4 4 4 5 5 6 6 7 8 8]

so i want to Find that on index 2,3,4,5,6 values or same or not ?

Note: Index can be Dynamically Entered.
Number(length) of Values in Array also can be changed..

To check if they are all equal: use diff to subtract pairs of values, and then check if all those differences are 0.

A = [2 2 3 3 3 4 4 4 5 5 6 6 7 8 8];
ind = [2 3 4 5 6];
result = ~any(diff(A(ind)));

This is faster than using unique . With A and ind as in your example,

>> tic
for cont = 1:1e5
    result = ~any(diff(A(ind)));
end
toc

tic
for cont = 1:1e5
    result=numel(unique(A(ind)))==1;
end
toc

Elapsed time is 0.371142 seconds.
Elapsed time is 4.754007 seconds.

Hey this should do the trick:

A= [2 2 3 3 3  4 4 4 5 5 6 6 7 8 8];

B= [1,3,5];

C=A(B);
result=numel(unique(C))==1;

Here A is your data. B is the index vector. C contains the elements corresponding to the index vector. result is 1 if all values were the same and 0 otherwise.

You can even "shorten" the code further by joining the two line:

result=numel(unique(A(B)))==1;

There are some ways, it depends on your taste.

For example, if the variable indexing contain the corresponding indexes:

unique(A(indexing));

will give you a vector with the unique elements in the sub-vector A(indexing) . Then you just need to check the length:

length(unique(A(indexing))) == 1

I would avoid the use of numel when the function length is available (it is much more clearer what you are trying to achieve).

Other option is to compare the first element to the rest of the element in the sub-vector:

sub_vector = A(indexing);
all(sub_vector == sub_vector(1));

The second option assumes that the sub-vector will never be empty!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM