Adding only present variables
1 次查看(过去 30 天)
显示 更早的评论
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!!!
0 个评论
采纳的回答
Walter Roberson
2012-9-5
Assign 0's to the variables before you do the load(), so that they will be sure to exist.
0 个评论
更多回答(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
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!