显然我可以用循环来做这个,但是我想知道在MATLAB中是否有更规范的方法。
假设我有一个充满结构类型的单元格数组(不是结构数组)。每个结构都有一个id字段。我想找到id为n的实例。所以,用更多的“MATLAB-Y”代替这个循环:
X = % get some cell array
c = repmat(X{1}, 1);
for i = 1:numel(X)
if X{i}.id == n
c = X{i};
break;
end
end
% use c
答案 0 :(得分:3)
代码使用 cell2mat
和 struct2cell
,并在代码的评论中进行了讨论。
代码 -
%// First convert the cell array to a numeric array using cell2mat,
%// which will essentially open up the inner struct.
s1 = cell2mat(X)
%// Convert the struct to a cell array using struct2cell such that each row would
%// have data from each of its field -
y1 = struct2cell(s1)
d1 = y1(getfield(s1, 'id'),:) %// Get data from only 'id' field as a cell array
%// Finally try to match n with the values in d1 after converting it to a
%// double array using cell2mat
c = X{find(cell2mat(d1)==n,1)}
答案 1 :(得分:3)
假设您的字段无法比拟,请使用:
X{find(cellfun(@(x)(x.('id')==n),X),1,'first')}
否则,使用:
转换为结构S=[X{:}];
X{find([S.id]==n,1)}