Compare a string to all values in column and extract rows where such Strings are found
조회 수: 3 (최근 30일)
이전 댓글 표시
There all I need help. I have a string that am comparing to all other strings in a column of an n-by-5 matrix. I thought its that simple but the extraction has empty matrix. I am at a fix here I need assistance. I loaded a .'mat' file containing the table and tried to extract according to the code below:
load('ds_nyc.mat');
NYCdata_extract=ds_nyc(:,[1 4:6 8]);
n=size(NYCdata_extract,1);
getBank=[];
tf=[];
for x=1:n
tf=strcmp('NYCdata_extract(x,2)','Bank');
if (tf==1)
getBank(x,:)=NYCdata_extract(x,:);
end
end
Any assistance will be deeply appreciated. Please see the attached file for clarity of the what I wanted to do.
댓글 수: 0
답변 (2개)
Guillaume
2016년 5월 23일
tf=strcmp('NYCdata_extract(x,2)','Bank');
compares the string 'NYCdata_extract(x,2)' to the string 'Bank', not the content of NYCdata_extract(x,2). Since the two strings are not the same, tf is always going to be false. The correct instruction should have been
tf = strcmp(NYCdata_extract(x,2),'Bank'); %no quote around the variable name.
Of course, since strcmp can compare a whole column of strings with a single string, the loop is completely unnecessary. All that is needed is:
load('ds_nyc.mat');
NYCdata_extract = ds_nyc(:,[1 4:6 8]);
getBank = NYCdata_extract(strcmp(NYCdata_extract(:, 2),'Bank'), :)
댓글 수: 2
Guillaume
2016년 5월 23일
I missed that you were using a dataset. As far as I know, the only way to extract the column of a dataset as a cell array is to use the column name:
load('ds_nyc.mat');
NYCdata_extract = ds_nyc(:,[1 4:6 8]);
getBank = NYCdata_extract(strcmp(NYCdata_extract.category_name,'Bank'), :)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!