필터 지우기
필터 지우기

Adding only present variables

조회 수: 2 (최근 30일)
Brett
Brett 2012년 9월 5일
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!!!

채택된 답변

Walter Roberson
Walter Roberson 2012년 9월 5일
Assign 0's to the variables before you do the load(), so that they will be sure to exist.

추가 답변 (1개)

Image Analyst
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
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

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by