フィルターのクリア

How to Exclude Some Fields While Using the Function structfun?

16 ビュー (過去 30 日間)
Rightia Rollmann
Rightia Rollmann 2017 年 3 月 5 日
回答済み: Jari Braeckman 2021 年 9 月 7 日
A.B.C = [1 2 3];
A.B.D = [3 4 5];
A.B.E = [6 7 8];
How to exclude A.B.E from the calculation and just get the sums of A.B.C and A.B.D (i.e., g = [4 6 8])?
for i = 1 : 3
z = structfun(@(x) x(i), A.B);
g(1, i) = sum(z);
end
g
  1 件のコメント
dpb
dpb 2017 年 3 月 5 日
structfun doesn't have an except clause; think you'll have to use dynamic field names and looping to accomplish this programmatically.
The simple answer for the specific case that doesn't generalize well and is probably not the actual question, either, is just
sum([A.B.C;A.B.D])

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2017 年 3 月 5 日
I assume this is related to your previous question. First, I'd like to point out that it doesn't look like a structure is the right container for your data. Since you want to do the same operations on all or most the fields, a cell array (or a matrix if the content of the fields is the same size) would be a lot better.
That's also the way to solve this particular problem. You can't do it with structfun.
A.B.C = [1 2 3];
A.B.D = [3 4 5];
A.B.E = [6 7 8];
c = struct2cell(A.B); %convert to cell array. In this particular case, a matrix would work even better
%you can then filter rows (fields) of the cell array any way you want,e .g.
fn = fieldnames(A.B);
filteredc = c(~ismember(fn, {'E', 'G'})); %remove fields 'E' and 'G'
s = sum(cell2mat(filteredc))

その他の回答 (1 件)

Jari Braeckman
Jari Braeckman 2021 年 9 月 7 日
It should work like this
for i = 1 : 3
z = structfun(@(x) x(i), rmfield(A.B,'E'));
g(1,i) = sum(z);
end

Community Treasure Hunt

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

Start Hunting!

Translated by