Compare a string to all values in column and extract rows where such Strings are found
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Azzi Abdelmalek
el 23 de Mayo de 2016
idx=ismember(NYCdata_extract(x,2),'Bank')
out=NYCdata_extract(idx,:)
Guillaume
el 23 de Mayo de 2016
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 comentarios
Guillaume
el 23 de Mayo de 2016
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'), :)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!