2014-11-19 4 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

은 귀하의 질문은 거의 완전히 "개별 변수로 저장 구조 필드"에서 save() 명령에 docs에 덮여있다. 그곳에 가려면 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

@ ;-) 끝났습니다. 내 코드가 완벽하게 실행됩니다. –