2011-10-28 2 views
1

나는 SIMULINK에서 EML (Embedded Matlab) 함수 블록 내부의 MATLAB 작업 공간에 형성된 구조를 반복하려고하는로드 블록에 부딪혔다. 여기에 몇 가지 예제 코드는 다음과 같습니다Simulink의 Embedded Matlab Function에서 구조체를 반복하는 방법은 무엇입니까?

% Matlab code to create workspace structure variables 
% Create the Elements 
MyElements = struct; 
MyElements.Element1 = struct; 
MyElements.Element1.var1 = 1; 
MyElements.Element1.type = 1; 
MyElements.Element2 = struct; 
MyElements.Element2.var2 = 2; 
MyElements.Element2.type = 2; 
MyElements.Element3 = struct; 
MyElements.Element3.var3 = 3; 
MyElements.Element3.type = 3; 

% Get the number of root Elements 
numElements = length(fieldnames(MyElements)); 

MyElements는 MATLAB 펑션 블록 SIMULINK에서 (EML)에 대한 버스 유형 매개 변수입니다. 아래는 내가 곤경에 처하게되는 부분입니다. 내 구조체 내부의 요소 수를 알고 이름을 알고 있지만 요소의 수는 구성에 따라 변경 될 수 있습니다. 따라서 Element 이름을 기반으로 하드 코딩 할 수는 없습니다. EML 블록 내부의 구조체를 반복해야합니다.

function output = fcn(MyElements, numElements) 
%#codegen 
persistent p_Elements; 

% Assign the variable and make persistent on first run 
if isempty(p_Elements) 
    p_Elements = MyElements;  
end 

% Prepare the output to hold the vars found for the number of Elements that exist 
output= zeros(numElements,1); 

% Go through each Element and get its data 
for i=1:numElements 
    element = p_Elements.['Element' num2str(i)]; % This doesn't work in SIMULINK 
    if (element.type == 1) 
     output(i) = element.var1; 
    else if (element.type == 2) 
     output(i) = element.var2; 
    else if (element.type == 3) 
     output(i) = element.var3; 
    else 
     output(i) = -1; 
    end 
end 

내가 SIMULINK에서 구조체 유형을 반복하는 방법에 대한 의견이 있으십니까? 또한 num2str과 같은 외부 함수는 대상 시스템에서 컴파일되므로 사용할 수 없습니다.

답변

2

구조에 dynamic field names을 사용하려고합니다. 올바른 구문은 다음과 같아야합니다.

element = p_Elements.(sprintf('Element%d',i)); 
type = element.type; 
%# ... 
관련 문제