2016-07-01 65 views
2

我想兩個字符串由兩個結構進行比較。我的代碼如下所示:Matlab的:比較的字符串循環

%MATLAB模型掃描

[variables] = Simulink.findVars('myModell'); 
variablesNames =[]; 

%save the names of all the variables in variablesNames 
for t= 1:length(variables) 
    variablesNames(t).Name = variables(t).Name; 
end 

%scan workspace 
for f = fieldnames(my_workspace) 
    found = false; 
    for c = 1:length(variablesNames) 
     if strcmp(f{c}, variablesNames(c))   
      found = true; 
      result = 'Found in Workspace: '; 
     end  
     if ~found 
      result = 'Not found inside Workspace'; 
     end 
    end 
    disp(['Workspace Variable: ', sprintf('%-*s',40,f{c}), result]); 
end 

variablesNames是一個結構×15與1場

my_workspace是1x1的結構與20場

我只有一個變量作爲返回。 這段代碼有什麼問題?

+0

'f = fieldnames(my_workspace)'?你的意思是'f = 1:numel(fieldnames(my_workspace))'? –

+0

你的意思是「結果」中只有一個值?這是非常正常的,因爲您每次循環都會覆蓋它。嘗試改變'result'到'結果{C}' – BillBokeey

+0

@Ander Biguri:我想你的建議,但請考慮**他媽的是20X1單元。以下是失敗:來自非單元格數組對象的單元格內容引用。 錯誤計算器(13號線) 如果的strcmp(F {C},variablesNames(c))的 – lara

回答

2

我真的不明白你爲什麼要在這裏創建一個新的結構:variablesNames(t).Name,所以我只是刪除該部分。

修改後的代碼只是通過variables結構陣列,並檢查變量my_workspace是否具有與存儲在當前處理的元件的Name字段中的值的名稱的字段進行迭代,使用isfield

[variables] = Simulink.findVars('myModell'); 

for i = 1:length(variables) 
    if isfield(my_workspace, variables(t).Name) 
     result = 'Found in Workspace: '; 
    else 
     result = 'Not found inside Workspace'; 
    end 

    disp(['Workspace Variable: ', sprintf('%-*s', 40, variables(t).Name), result]); 
end