2014-11-19 5 views
1

Примечание: Пожалуйста, если вы можете указать решение без 'eval', это было бы здорово !!! Если нет, то я буду благодарен тоже :-) Ну, у меня есть клетка (Var_s), который имеет в первых строках строк и во второй матрицы строк:Ячейки Matlab с именами

clc 
clearvars 
fclose all 

L=[11 22 33 44]; 
M=[1 2 3]; 
N=[101 102 103 104 105, 95 96 97 98 99]; 
Var_s=cell(2,3); 
Var_s(1,1:3)={'Rn', 'LE', 'O'}; %// The strings are all different and were not created in a loop. 
Var_s(2,1:3)={L, M, N};   %// No correlation is possible. 


%//Than I delete all variables because I can work with the cell (Var_s{2,:}) 
%//to execute some computations 
clearvars L M N 


%//Now I want to save the values which are stored inside of the cells in the 
%//second line of Var_s, Var_s{2,:}, associating to them the names in the first 
%//row of the Var_s, Var_s{1,:}, in a .mat file 
%//But let's imagine that instead of having size(Var_s{2,:})=3 I would have 
%//something like 1000 (but lets keep it simple for now having just 3). 
%//Consequently I want to use a 'for' to do this work! 
%//And it is at this point that the issue appears. How can I use the strings 
%//inside Var_s{1,:} to create variables and store them in the .mat file with 
%//the values in the cells of Var_s{2,:} associated to them? 


filename='Clima'; 
a=0; 
save(filename,'a'); %//Creats the file with a variable a=0 


for i=1:length(Var_s(2,:)) 
genvarname(Var_s{1,i})=Var_s{2,i}; %//The idea is to create a variable using a stringn and associate the values 
save(filename,char(Var_s{1,i}),'-append'); %//The idea is to add the created variable that has the same name in Var_s{1,i} 
end 
clearvars 


%//After all this I could access the variables that are stored in 'Clima.mat' 
%//by their name such as 
load('Clima.mat') 
Rn 
LE 
O 

И результат должен быть

Rn = 11 22 33 44 
    LE = 1 2 3 
    N = 101 102 103 104 105 
+1

Пожалуйста, оставьте код-код для кода и поместите свои текстовые пояснения вне форматирования кода для будущих вопросов (и, возможно, отредактируйте этот вопрос соответственно). – Nras

ответ

5

Ваш вопрос в значительной степени полностью покрыты в docs команде save() под «Сохранить структуру полей в виде отдельных переменных». Чтобы попасть туда, вы должны создать только struct.

Чтобы создать это struct(), где вы динамически создаете свои имена полей, вы не должны изменять свой код. Когда ваша структура создается в этом цикле, просто сохраните структуру один раз после цикла с опцией '-struct', которая автоматически генерирует новую переменную для каждого поля в этой структуре.

s = struct(); 
for i=1:length(Var_s(2,:)) 
    s.(Var_s{1,i})=Var_s{2,i}; % struct with dynamic field names 
end 
save(filename, '-struct', 's'); 

Теперь давайте посмотрим, что мы сохранили:

whos('-file', 'Clima.mat') 
    Name  Size   Bytes Class  Attributes 

    LE  1x3    24 double    
    O   1x10    80 double    
    Rn  1x4    32 double 

Как вы можете видеть, мы сохранили 3 переменные в этом файле.

+0

Отличный ответ! Оно работает! Много раз случается, что я не знаю, где найти объяснения в помощи Matlab. Спасибо –

+0

@JohnazGrynn Рад помочь. Поскольку вы не знакомы с этим сайтом: когда появляется ответ, чтобы решить вашу проблему, вы можете принять ответ. – Nras

+0

@ ;-) Все готово. Мой код работает в совершенстве. –

Смежные вопросы