Help in making code involving strings and cell array simpler and run faster

1 次查看(过去 30 天)
Dear All,
Is there any to make this code simpler? It involves detecting a value a from a string to see if it is equal to value in a cell array and then recording the index of the string the value is contained in. i.e if xx=[1,2,3] and a = [{1,98,99} {1,2,6,} {4,5,6} {7,8,9} {3,45,78}], then y should equal [1,2,5] as those strings contain th values in the xx.
a=groups;
xx=string;
y=[];
for i = 1:length(a)
for j = a{i}
for k = xx
if k == j
y = [y i];
end
end
end
end
y = unique(y);
Sorry if I am not clear in asking this question, I have only been doing Matlab for a short time.When i have tried to run this code using the a and xx i have, it simply runs on and on without giving an answer or error.
Kind Regards,
Blixan

采纳的回答

Stephen23
Stephen23 2017-3-6
编辑:Stephen23 2017-3-6
Your syntax is not correct. In MATLAB [] is not a list operator, it is a concatenation operator. So your code does not form a "list": it simply concatenates all of those cell arrays into one single cell array. You can check this out yourself:
>> a = [{1,98,99} {1,2,6} {4,5,6} {7,8,9} {3,45,78}];
>> class(a)
ans = cell
>> size(a)
ans =
1 15
To perform your task you should create a cell array of numeric arrays, like this:
>> a = {[1,98,99],[1,2,6],[4,5,6],[7,8,9],[3,45,78]};
>> xx = [1,2,3];
>> idx = cellfun(@(v)any(ismember(v,xx)),a)
idx =
1 1 0 0 1
The vector idx gives the logical indices: logical indices are often faster and simpler to use than any other indices, but if you really need the subscript indices then use find:
>> find(idx)
ans =
1 2 5

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by