Adding only present variables
이전 댓글 표시
Hi Matlab friends, you guys are the best! What I am trying to do is some up a bunch of variable values, however, if the variable isn't present, the program crashes. How do I make it so it only sums the present variable values.
Here is my code:
evalin('base','save LSCvars.mat');
load LSCvars.mat
T1 = Q30 + Q29 + Q28 + Q27 + Q26 + Q25 + Q24
assignin('base','T1',T1)
T2 = D1 + D2 + D3 + D4 + D5 + D6 + D7 + D8
assignin('base','T2',T2)
T3 = (B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8)/T1
assignin('base','T3',T3)
Thanks!!!
채택된 답변
추가 답변 (1개)
Image Analyst
2012년 9월 6일
편집: Image Analyst
2012년 9월 6일
Don't use evalin and assignin. Read in the mat file, then go through all the variables you expect to be there. If it's there, add it to your "T" variables. If it's not there for some reason, then nothing will get added.
T1 = 0;
T2 = 0;
T3 = 0;
storedStructure= load('LSCvars.mat')
hasField = isfield(storedStructure, 'Q24');
if hasField
T1 = T1 + Q24;
end
hasField = isfield(storedStructure, 'Q25');
if hasField
T1 = T1 + Q25;
end
and so on for the other T's and Q's.
댓글 수: 1
Walter Roberson
2012년 9월 6일
T1 = 0;
for field_name = {'Q24', 'Q25', 'Q30'} %etc
if isfield(storedStructure, field_name)
T1 = T1 + storedStructre.(field_name);
end
end
카테고리
도움말 센터 및 File Exchange에서 Variables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!