cannot search for index of multiple elements in a larger array

5 views (last 30 days)
I have an array containing 44 location indices
A =
Columns 1 through 11
1027 1471 1963 2458 2913 3392 3897 4418 4918 5409 5920
Columns 12 through 22
6441 6959 7441 7914 8426 8899 9378 9852 10339 10848 11361
Columns 23 through 33
11876 12368 12880 13404 13928 14454 14973 15477 16021 16528 17004
Columns 34 through 44
17487 17980 18508 19008 19487 19978 20473 20978 21454 21738 22380
>>
I have another smaller array
i =
1027 8426 21738 22380
I need to find the indices of the elements of the smaller array in the larger array
I am trying to use the find command as follows;
>> j=find(A == i)
Gives error message
Matrix dimensions must agree.
note:
size(A)
ans =
1 44
>> size(i)
ans =
1 4
What am I doing wrong?

Accepted Answer

Walter Roberson
Walter Roberson on 7 Aug 2025
You do not promise that there will be exactly one match for each element of i, so you need to do something like
A = [ 1027 1471 1963 2458 2913 3392 3897 4418 4918 5409 5920 ...
6441 6959 7441 7914 8426 8899 9378 9852 10339 10848 11361 ...
11876 12368 12880 13404 13928 14454 14973 15477 16021 16528 17004 ...
17487 17980 18508 19008 19487 19978 20473 20978 21454 21738 22380
];
i = [1027 8426 21738 22380];
arrayfun(@(VAL) find(A==VAL), i, 'uniform', 0)
ans = 1×4 cell array
{[1]} {[16]} {[43]} {[44]}
If you can promise exactly one match then
[~,IDX] = ismember(i, A)
IDX = 1×4
1 16 43 44
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
In this later code, any member of i that is not matched will result in an entry of 0 in IDX

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!