Given a spreadsheet with variables in columns and observations in rows, I would like to selectively import those observations into MATLAB whose value in a specified column is equal to a specified string (in this case 'K'
). I am aware of the possibility to use a loop but my data set is very large and I would prefer a faster solution (logical indexing?). I am using a table variable.
I would greatly appreciate any suggestions. I have found multiple solutions online to do this for array variables, but not for table variables.
My spreadsheet looks like this:
Variable1 Variable2 Variable3
234789 234678234 'K'
98764 087632167 'V'
87641 492876437 'V'
43789234 123678923 'K'
In this example I would only want to import rows 1 and 4 (not counting headers) because they have value 'K'
for Variable3
.
I have tried tableName(tableName(:,3) ~= 'K', :) = []
after importing the entire dataset but I get an Undefined operator '~=' for input arguments of type 'table'
error message.
Ok there is probably a better answer but here is what I know. I've never been able to use this kind of logic:
tableName(tableName(:,3) ~= 'K', :) = []
Even if you were using the correct kind of logical comparison between something in a table and a character (table ~= 'K') you will probably have issues with the way you are trying to use the logic.
To do what you want without looping, I typically create a temporary variable that contains only the column of the variable that will determine which rows to keep. Here's an example of what I mean...
data = {1,2,'b';3,4,'c';5,6,'d';7,8,'d'};
%find which rows where the third column is 'd'
temp = data(:,3);%create temporary variable
out = strcmp(temp,'d');%returns logical 1 where strings are the same
index = find(out);%returns the indexes of which rows contain 'd'
data = data(index,:);%now you only have the rows containing 'd'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.