Info

此问题已关闭。 请重新打开它进行编辑或回答。

How do I create a table from a larger table that is filtered on specific entries of data?

1 次查看(过去 30 天)
I am trying to write part of a function that takes a table of strings and 7 string values from within the table and creates a new table with only the rows that have the given values. vMaint, vDoors, etc are strings that are also present within the table and dataArray is the table (favoredBuy isn't important for this question). When I run my code I am given an error that the '==' operator is not valid for values of type cell. How can I change this to create a table that contains only the rows that match the input strings?
function result = conditionBuying(favoredBuy,vMaint,vDoors,vPersons,vLugBoot,vSafety,vAcceptable,dataArray)
fTable = dataArray(dataArray.maint == vMaint...
&& dataArray.doors == vDoors...
&& dataArray.persons == vPersons...
&& dataArray.lug_boot == vLugBoot...
&& dataArray.safety == vSafety...
&& dataArray.acceptability == vAcceptable,:);

回答(1 个)

Image Analyst
Image Analyst 2016-10-2
The variable (column) is a cell array of strings, so you need to use strcmpi() or strcmp() instead of ==. See this demo:
% Create Table from Workspace Variables
% Define workspace variables with the same number of rows.
LastNames = {'Johnson';'Roberson';'Simon';'Greene';'Analyst'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
% Create a table, |T|, as a container for the workspace variables.
T = table(LastNames, Age,Height,Weight,BloodPressure)
% Extract the LastName column so we can see it's a cell array.
ca = T.LastNames
whos ca
% See it work with strcmpi()
rowsToExtract = strcmpi(ca, 'Johnson')
output = T(rowsToExtract, :)
% Now see it fail with ==
matches = (ca == 'Johnson')

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by