필터 지우기
필터 지우기

How to sum the values of a fieldname of struct

조회 수: 14 (최근 30일)
Chao Zhang
Chao Zhang 2021년 7월 18일
댓글: Image Analyst 2021년 7월 19일
Hello! I have a struct 'STC_ORE', and I want to calculate the values of fieldname' ORE_TON', so I want a code, but there are some errors. Therefore, could you please give me some solutions to deal with it, thanks!
for ii = 1:size(rock_code,1)
if ~isempty(STC_ORE(ii).ORE_TON)
A=sum([STC_ORE(:).ORE_TON]);
end
end

채택된 답변

Image Analyst
Image Analyst 2021년 7월 18일
You need to add the sum onto the prior value of the sum:
theSum = 0; % Initialize
for ii = 1:size(rock_code,1)
if ~isempty(STC_ORE(ii).ORE_TON)
theSum = theSum + sum([STC_ORE(:).ORE_TON]); % Add onto running total.
end
end
If you need more help, or that doesn't work, attach STC_ORE in a .mat file.
  댓글 수: 2
Chao Zhang
Chao Zhang 2021년 7월 18일
theSum = theSum + sum([STC_ORE(ii).ORE_TON]) might works well
Image Analyst
Image Analyst 2021년 7월 19일
Yeah, but it's not a bad idea to check like you did. Sometimes doing math on null/empty or NaN values will throw an error or make the whole thing be NaN.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by