Find exact vector order in another vector array

조회 수: 9 (최근 30일)
Alyssa
Alyssa 2024년 4월 23일
편집: Voss 2024년 4월 23일
I am trying to find a way to grab indivdual cells within a cell array that I can then use to find the exact order found in a larger matrix array.
I am having a difficult time trying to find a way to grab the exact order/vector in each cell array to locate the indices in the second larger matrix array.
For example, my cell array "att_event_codes" is the array I'm grabbing my desired vectors to find in the larger matrix array:
att_event_codes{1,1} : 9 10 12 11 20 12 33 21 42 22 18
att_event_codes{1,2}: 9 10 12 11 20 12 33 21 40 41 22 18
If I grab, for example, att_event_codes{1,1} as a vector I want to use:
vector = (att_event_codes{1,1});
I want to take that vector assignment to find the exact order of event codes in my larger matrix called "event_codes" (1x19277 double).
I have tried several matlab functions such as find, ismember, and strcmp and have been unable to figure out how to get them to work taking into account the entire vector rather than working with individual items within the vector. For example:
vector = (att_event_codes{1,1});
mask = ismember(event_codes,vector);
test = find(mask)
test returns 1x14953 double
Another way that I've tried (which is probably a better way to do this):
[~,test] = ismember(vector, event_codes)
test returns 1x11 double:
1 2 3 8 4 3 25 11 3655 5 15
The correct (desired) answser for this "test" would return an index of 3647:3657.
Thank you.

채택된 답변

Voss
Voss 2024년 4월 23일
편집: Voss 2024년 4월 23일
If I understand correctly, you want to find where in a large vector (event_codes, size 1x19277) a small vector (e.g., att_event_codes{1,1}, size 1x11) can be found. The smaller vector must be in the same order and contiguous in the larger vector. If that's the case, you can use strfind. Here's an example:
% construct example large vector and cell array containing small vector:
att_event_codes = {[9 10 12 11 20 12 33 21 42 22 18]};
event_codes = randi(50,1,19277);
% make elements 3647 to 3657 of event_codes match att_event_codes{1}:
event_codes(3647:3657) = att_event_codes{1};
% use strfind to find the start index of all matches of att_event_codes{1} in event_codes:
idx = strfind(event_codes,att_event_codes{1});
if isempty(idx)
% no match
test = [];
else
% at least one match;
% take the first match and add index offsets to the length of att_event_codes{1}
test = idx(1) + (0:numel(att_event_codes{1})-1);
end
% check the result
disp(test)
3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
  댓글 수: 2
Alyssa
Alyssa 2024년 4월 23일
Hello, this works for my code, thank you so much!
Voss
Voss 2024년 4월 23일
편집: Voss 2024년 4월 23일
You're welcome! Any questions, let me know.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by