简体   繁体   中英

How to find the position of a value in an array in matlab

Think I have an array like A = { 1,2,3,4,5,6} I need to get the position of 4 in this array. I tried, p = find(A==4)

Please help.

If you really need a cell array (for example because the cells can contain vectors of different sizes):

A = {1, [1 2 3], 4, [1 2], [3 4]}; %// example cell array
sought = [1 2]; %// sought contents
index = find(cellfun(@(x) isequal(x, sought), A));

you created a cell-array instead of a normal vector.

Try:

A = [1,2,3,4,5,6]
find(A==4)

Cell arrays are great to store variables with different types.You could, for example, create a cell array that contains strings as well as digits.

If you have only digits in your array you should defintely use normal arrays. These are defined by [ ] instead of { }

As you have defined a cell array you need to convert it to a numeric array for find to work, fortunately this is simple to achieve with a couple of well placed brackets.

A = { 1,2,4,3,5,6};

find([A{:}]==4)

ans =

     3

So A{:} writes out the numeric values from your array and the [] contains the output for find to work.

ps I re-arranged the numbers in A to show that it was working as '4' is now in position 3 to provide a better test.

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