Azzera filtri
Azzera filtri

Adding only present variables

2 visualizzazioni (ultimi 30 giorni)
Brett
Brett il 5 Set 2012
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!!!

Risposta accettata

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

Più risposte (1)

Image Analyst
Image Analyst il 6 Set 2012
Modificato: Image Analyst il 6 Set 2012
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 Commento
Walter Roberson
Walter Roberson il 6 Set 2012
T1 = 0;
for field_name = {'Q24', 'Q25', 'Q30'} %etc
if isfield(storedStructure, field_name)
T1 = T1 + storedStructre.(field_name);
end
end

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by