1
我遇到了一個障礙,我試圖通過在SIMULINK中的EML(嵌入式Matlab)功能塊內的MATLAB工作區中形成的結構進行迭代。下面是一些示例代碼:如何迭代Simulink中嵌入式Matlab函數中的結構?
% 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的功能塊(EML)在SIMULINK一個總線類型參數。以下是我遇到麻煩的地區。我知道結構中的元素數量,我知道這些名稱,但元素的數量可以隨着任何配置而改變。所以我不能基於元素名稱進行硬編碼。我必須遍歷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這樣的任何外部函數,因爲這是在目標系統上編譯的。