Create a row vector comparing strings in a for loop

조회 수: 1 (최근 30일)
Lorenzo Amedeo
Lorenzo Amedeo 2023년 1월 18일
댓글: Lorenzo Amedeo 2023년 1월 19일
I have two string arrays with different sizes and assume that the second one (s2) has a variable size.
I need to create a vector (index) that contains only the indices where 'strcmpi' returns the logical value 1. It works if 's2' contains only strings present in 's1', otherwiswe the following error occurs. I think that's because I am assigning to 'index' the size of 'k' but there will be only 3 logical value = 1, but I don't know how to fix it.
Any help would be appreciated. Thanks.
s1 = { 'FMO1','FMO2','FMO3','FMO4', 'BAO1', 'BAO2', 'BAO3', 'BAO4'};
s2 = {'mean','FMO1','BAO4','FMO2'};
for k = 1 : length(s2)
compare = strcmpi(s2{k},s1);
index(k) = find(compare==1)
end
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
  댓글 수: 1
Lorenzo Amedeo
Lorenzo Amedeo 2023년 1월 18일
Also thanks to you, do I have to accept your answer too? even if I already accepted the previous one

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

채택된 답변

Davide Masiello
Davide Masiello 2023년 1월 18일
index = [];
s1 = { 'FMO1','FMO2','FMO3','FMO4', 'BAO1', 'BAO2', 'BAO3', 'BAO4'};
s2 = {'mean','FMO1','BAO4','FMO2'};
for k = 1 : length(s2)
compare = strcmpi(s2{k},s1);
index = [index,find(compare==1)];
end
index
index = 1×3
1 8 2
This way, even if any of the entry in s2 appears several times in s1 you should be ok.
  댓글 수: 2
Lorenzo Amedeo
Lorenzo Amedeo 2023년 1월 18일
Problem solved, thanks.
Stephen23
Stephen23 2023년 1월 18일
Expanding the output array will be inefficient.

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

추가 답변 (1개)

Stephen23
Stephen23 2023년 1월 18일
The simple MATLAB approach:
s1 = { 'FMO1','FMO2','FMO3','FMO4', 'BAO1', 'BAO2', 'BAO3', 'BAO4'};
s2 = {'mean','FMO1','BAO4','FMO2'};
X = contains(s1,s2)
X = 1×8 logical array
1 1 0 0 0 0 0 1
Y = find(X) % optional
Y = 1×3
1 2 8
  댓글 수: 1
Lorenzo Amedeo
Lorenzo Amedeo 2023년 1월 19일
Thank you, I would accept your answer but I don't think I can accept more than one.

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by