[英]How to conditionally import data from a spreadsheet into MATLAB without using a loop
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'
). 给定一个在列中具有变量且在行中具有观察值的电子表格,我想将这些观察值有选择地导入到MATLAB中,该值在指定列中的值等于指定的字符串(在本例中为
'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
. 在此示例中,我只想导入第1行和第4行(不计算标题),因为它们的
Variable3
值为'K'
。
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. 导入整个数据集后
tableName(tableName(:,3) ~= 'K', :) = []
我尝试了tableName(tableName(:,3) ~= 'K', :) = []
,但Undefined operator '~=' for input arguments of type 'table'
错误消息Undefined operator '~=' for input arguments of type 'table'
我得到了Undefined operator '~=' for input arguments of type 'table'
。
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. 即使您在表和字符(表〜='K')之间使用了正确的逻辑比较,您可能也会在尝试使用逻辑的方式上遇到问题。
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.